Warning: file_get_contents(https://raw.githubusercontent.com/Den1xxx/Filemanager/master/languages/ru.json): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 88
Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 215
Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 216
Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 217
Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 218
Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 219
Warning: Cannot modify header information - headers already sent by (output started at /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php:88) in /home/afelisqd/cppseducation.sc.tz/admin/images/photos/17587263121019776732_admin-dbb.php on line 220
PK ! TEN N Cipher/test_CBC.pynu [ # ===================================================================
#
# Copyright (c) 2014, Legrandin
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ===================================================================
import unittest
from binascii import unhexlify
from Crypto.SelfTest.loader import load_test_vectors
from Crypto.SelfTest.st_common import list_test_cases
from Crypto.Util.py3compat import tobytes, is_string
from Crypto.Cipher import AES, DES3, DES
from Crypto.Hash import SHAKE128
def get_tag_random(tag, length):
return SHAKE128.new(data=tobytes(tag)).read(length)
class BlockChainingTests(unittest.TestCase):
key_128 = get_tag_random("key_128", 16)
key_192 = get_tag_random("key_192", 24)
iv_128 = get_tag_random("iv_128", 16)
iv_64 = get_tag_random("iv_64", 8)
data_128 = get_tag_random("data_128", 16)
def test_loopback_128(self):
cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
pt = get_tag_random("plaintext", 16 * 100)
ct = cipher.encrypt(pt)
cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
pt2 = cipher.decrypt(ct)
self.assertEqual(pt, pt2)
def test_loopback_64(self):
cipher = DES3.new(self.key_192, self.des3_mode, self.iv_64)
pt = get_tag_random("plaintext", 8 * 100)
ct = cipher.encrypt(pt)
cipher = DES3.new(self.key_192, self.des3_mode, self.iv_64)
pt2 = cipher.decrypt(ct)
self.assertEqual(pt, pt2)
def test_iv(self):
# If not passed, the iv is created randomly
cipher = AES.new(self.key_128, self.aes_mode)
iv1 = cipher.iv
cipher = AES.new(self.key_128, self.aes_mode)
iv2 = cipher.iv
self.assertNotEqual(iv1, iv2)
self.assertEqual(len(iv1), 16)
# IV can be passed in uppercase or lowercase
cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
ct = cipher.encrypt(self.data_128)
cipher = AES.new(self.key_128, self.aes_mode, iv=self.iv_128)
self.assertEqual(ct, cipher.encrypt(self.data_128))
cipher = AES.new(self.key_128, self.aes_mode, IV=self.iv_128)
self.assertEqual(ct, cipher.encrypt(self.data_128))
def test_iv_must_be_bytes(self):
self.assertRaises(TypeError, AES.new, self.key_128, self.aes_mode,
iv = u'test1234567890-*')
def test_only_one_iv(self):
# Only one IV/iv keyword allowed
self.assertRaises(TypeError, AES.new, self.key_128, self.aes_mode,
iv=self.iv_128, IV=self.iv_128)
def test_iv_with_matching_length(self):
self.assertRaises(ValueError, AES.new, self.key_128, self.aes_mode,
b"")
self.assertRaises(ValueError, AES.new, self.key_128, self.aes_mode,
self.iv_128[:15])
self.assertRaises(ValueError, AES.new, self.key_128, self.aes_mode,
self.iv_128 + b"0")
def test_block_size_128(self):
cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
self.assertEqual(cipher.block_size, AES.block_size)
def test_block_size_64(self):
cipher = DES3.new(self.key_192, self.des3_mode, self.iv_64)
self.assertEqual(cipher.block_size, DES3.block_size)
def test_unaligned_data_128(self):
cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
for wrong_length in range(1,16):
self.assertRaises(ValueError, cipher.encrypt, b"5" * wrong_length)
cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
for wrong_length in range(1,16):
self.assertRaises(ValueError, cipher.decrypt, b"5" * wrong_length)
def test_unaligned_data_64(self):
cipher = DES3.new(self.key_192, self.des3_mode, self.iv_64)
for wrong_length in range(1,8):
self.assertRaises(ValueError, cipher.encrypt, b"5" * wrong_length)
cipher = DES3.new(self.key_192, self.des3_mode, self.iv_64)
for wrong_length in range(1,8):
self.assertRaises(ValueError, cipher.decrypt, b"5" * wrong_length)
def test_IV_iv_attributes(self):
data = get_tag_random("data", 16 * 100)
for func in "encrypt", "decrypt":
cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
getattr(cipher, func)(data)
self.assertEqual(cipher.iv, self.iv_128)
self.assertEqual(cipher.IV, self.iv_128)
def test_unknown_parameters(self):
self.assertRaises(TypeError, AES.new, self.key_128, self.aes_mode,
self.iv_128, 7)
self.assertRaises(TypeError, AES.new, self.key_128, self.aes_mode,
iv=self.iv_128, unknown=7)
# But some are only known by the base cipher (e.g. use_aesni consumed by the AES module)
AES.new(self.key_128, self.aes_mode, iv=self.iv_128, use_aesni=False)
def test_null_encryption_decryption(self):
for func in "encrypt", "decrypt":
cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
result = getattr(cipher, func)(b"")
self.assertEqual(result, b"")
def test_either_encrypt_or_decrypt(self):
cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
cipher.encrypt(b"")
self.assertRaises(TypeError, cipher.decrypt, b"")
cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
cipher.decrypt(b"")
self.assertRaises(TypeError, cipher.encrypt, b"")
def test_data_must_be_bytes(self):
cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
self.assertRaises(TypeError, cipher.encrypt, u'test1234567890-*')
cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
self.assertRaises(TypeError, cipher.decrypt, u'test1234567890-*')
def test_bytearray(self):
data = b"1" * 128
data_ba = bytearray(data)
# Encrypt
key_ba = bytearray(self.key_128)
iv_ba = bytearray(self.iv_128)
cipher1 = AES.new(self.key_128, self.aes_mode, self.iv_128)
ref1 = cipher1.encrypt(data)
cipher2 = AES.new(key_ba, self.aes_mode, iv_ba)
key_ba[:3] = b'\xFF\xFF\xFF'
iv_ba[:3] = b'\xFF\xFF\xFF'
ref2 = cipher2.encrypt(data_ba)
self.assertEqual(ref1, ref2)
self.assertEqual(cipher1.iv, cipher2.iv)
# Decrypt
key_ba = bytearray(self.key_128)
iv_ba = bytearray(self.iv_128)
cipher3 = AES.new(self.key_128, self.aes_mode, self.iv_128)
ref3 = cipher3.decrypt(data)
cipher4 = AES.new(key_ba, self.aes_mode, iv_ba)
key_ba[:3] = b'\xFF\xFF\xFF'
iv_ba[:3] = b'\xFF\xFF\xFF'
ref4 = cipher4.decrypt(data_ba)
self.assertEqual(ref3, ref4)
def test_memoryview(self):
data = b"1" * 128
data_mv = memoryview(bytearray(data))
# Encrypt
key_mv = memoryview(bytearray(self.key_128))
iv_mv = memoryview(bytearray(self.iv_128))
cipher1 = AES.new(self.key_128, self.aes_mode, self.iv_128)
ref1 = cipher1.encrypt(data)
cipher2 = AES.new(key_mv, self.aes_mode, iv_mv)
key_mv[:3] = b'\xFF\xFF\xFF'
iv_mv[:3] = b'\xFF\xFF\xFF'
ref2 = cipher2.encrypt(data_mv)
self.assertEqual(ref1, ref2)
self.assertEqual(cipher1.iv, cipher2.iv)
# Decrypt
key_mv = memoryview(bytearray(self.key_128))
iv_mv = memoryview(bytearray(self.iv_128))
cipher3 = AES.new(self.key_128, self.aes_mode, self.iv_128)
ref3 = cipher3.decrypt(data)
cipher4 = AES.new(key_mv, self.aes_mode, iv_mv)
key_mv[:3] = b'\xFF\xFF\xFF'
iv_mv[:3] = b'\xFF\xFF\xFF'
ref4 = cipher4.decrypt(data_mv)
self.assertEqual(ref3, ref4)
def test_output_param(self):
pt = b'5' * 128
cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
ct = cipher.encrypt(pt)
output = bytearray(128)
cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
res = cipher.encrypt(pt, output=output)
self.assertEqual(ct, output)
self.assertEqual(res, None)
cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
res = cipher.decrypt(ct, output=output)
self.assertEqual(pt, output)
self.assertEqual(res, None)
def test_output_param_same_buffer(self):
pt = b'5' * 128
cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
ct = cipher.encrypt(pt)
pt_ba = bytearray(pt)
cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
res = cipher.encrypt(pt_ba, output=pt_ba)
self.assertEqual(ct, pt_ba)
self.assertEqual(res, None)
ct_ba = bytearray(ct)
cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
res = cipher.decrypt(ct_ba, output=ct_ba)
self.assertEqual(pt, ct_ba)
self.assertEqual(res, None)
def test_output_param_memoryview(self):
pt = b'5' * 128
cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
ct = cipher.encrypt(pt)
output = memoryview(bytearray(128))
cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
cipher.encrypt(pt, output=output)
self.assertEqual(ct, output)
cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
cipher.decrypt(ct, output=output)
self.assertEqual(pt, output)
def test_output_param_neg(self):
LEN_PT = 128
pt = b'5' * LEN_PT
cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
ct = cipher.encrypt(pt)
cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
self.assertRaises(TypeError, cipher.encrypt, pt, output=b'0' * LEN_PT)
cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
self.assertRaises(TypeError, cipher.decrypt, ct, output=b'0' * LEN_PT)
shorter_output = bytearray(LEN_PT - 1)
cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
self.assertRaises(ValueError, cipher.encrypt, pt, output=shorter_output)
cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
self.assertRaises(ValueError, cipher.decrypt, ct, output=shorter_output)
class CbcTests(BlockChainingTests):
aes_mode = AES.MODE_CBC
des3_mode = DES3.MODE_CBC
class NistBlockChainingVectors(unittest.TestCase):
def _do_kat_aes_test(self, file_name):
test_vectors = load_test_vectors(("Cipher", "AES"),
file_name,
"AES CBC KAT",
{ "count" : lambda x: int(x) } )
if test_vectors is None:
return
direction = None
for tv in test_vectors:
# The test vector file contains some directive lines
if is_string(tv):
direction = tv
continue
self.description = tv.desc
cipher = AES.new(tv.key, self.aes_mode, tv.iv)
if direction == "[ENCRYPT]":
self.assertEqual(cipher.encrypt(tv.plaintext), tv.ciphertext)
elif direction == "[DECRYPT]":
self.assertEqual(cipher.decrypt(tv.ciphertext), tv.plaintext)
else:
assert False
# See Section 6.4.2 in AESAVS
def _do_mct_aes_test(self, file_name):
test_vectors = load_test_vectors(("Cipher", "AES"),
file_name,
"AES CBC Montecarlo",
{ "count" : lambda x: int(x) } )
if test_vectors is None:
return
direction = None
for tv in test_vectors:
# The test vector file contains some directive lines
if is_string(tv):
direction = tv
continue
self.description = tv.desc
cipher = AES.new(tv.key, self.aes_mode, tv.iv)
if direction == '[ENCRYPT]':
cts = [ tv.iv ]
for count in range(1000):
cts.append(cipher.encrypt(tv.plaintext))
tv.plaintext = cts[-2]
self.assertEqual(cts[-1], tv.ciphertext)
elif direction == '[DECRYPT]':
pts = [ tv.iv]
for count in range(1000):
pts.append(cipher.decrypt(tv.ciphertext))
tv.ciphertext = pts[-2]
self.assertEqual(pts[-1], tv.plaintext)
else:
assert False
def _do_tdes_test(self, file_name):
test_vectors = load_test_vectors(("Cipher", "TDES"),
file_name,
"TDES CBC KAT",
{ "count" : lambda x: int(x) } )
if test_vectors is None:
return
direction = None
for tv in test_vectors:
# The test vector file contains some directive lines
if is_string(tv):
direction = tv
continue
self.description = tv.desc
if hasattr(tv, "keys"):
cipher = DES.new(tv.keys, self.des_mode, tv.iv)
else:
if tv.key1 != tv.key3:
key = tv.key1 + tv.key2 + tv.key3 # Option 3
else:
key = tv.key1 + tv.key2 # Option 2
cipher = DES3.new(key, self.des3_mode, tv.iv)
if direction == "[ENCRYPT]":
self.assertEqual(cipher.encrypt(tv.plaintext), tv.ciphertext)
elif direction == "[DECRYPT]":
self.assertEqual(cipher.decrypt(tv.ciphertext), tv.plaintext)
else:
assert False
class NistCbcVectors(NistBlockChainingVectors):
aes_mode = AES.MODE_CBC
des_mode = DES.MODE_CBC
des3_mode = DES3.MODE_CBC
# Create one test method per file
nist_aes_kat_mmt_files = (
# KAT
"CBCGFSbox128.rsp",
"CBCGFSbox192.rsp",
"CBCGFSbox256.rsp",
"CBCKeySbox128.rsp",
"CBCKeySbox192.rsp",
"CBCKeySbox256.rsp",
"CBCVarKey128.rsp",
"CBCVarKey192.rsp",
"CBCVarKey256.rsp",
"CBCVarTxt128.rsp",
"CBCVarTxt192.rsp",
"CBCVarTxt256.rsp",
# MMT
"CBCMMT128.rsp",
"CBCMMT192.rsp",
"CBCMMT256.rsp",
)
nist_aes_mct_files = (
"CBCMCT128.rsp",
"CBCMCT192.rsp",
"CBCMCT256.rsp",
)
for file_name in nist_aes_kat_mmt_files:
def new_func(self, file_name=file_name):
self._do_kat_aes_test(file_name)
setattr(NistCbcVectors, "test_AES_" + file_name, new_func)
for file_name in nist_aes_mct_files:
def new_func(self, file_name=file_name):
self._do_mct_aes_test(file_name)
setattr(NistCbcVectors, "test_AES_" + file_name, new_func)
del file_name, new_func
nist_tdes_files = (
"TCBCMMT2.rsp", # 2TDES
"TCBCMMT3.rsp", # 3TDES
"TCBCinvperm.rsp", # Single DES
"TCBCpermop.rsp",
"TCBCsubtab.rsp",
"TCBCvarkey.rsp",
"TCBCvartext.rsp",
)
for file_name in nist_tdes_files:
def new_func(self, file_name=file_name):
self._do_tdes_test(file_name)
setattr(NistCbcVectors, "test_TDES_" + file_name, new_func)
# END OF NIST CBC TEST VECTORS
class SP800TestVectors(unittest.TestCase):
"""Class exercising the CBC test vectors found in Section F.2
of NIST SP 800-3A"""
def test_aes_128(self):
key = '2b7e151628aed2a6abf7158809cf4f3c'
iv = '000102030405060708090a0b0c0d0e0f'
plaintext = '6bc1bee22e409f96e93d7e117393172a' +\
'ae2d8a571e03ac9c9eb76fac45af8e51' +\
'30c81c46a35ce411e5fbc1191a0a52ef' +\
'f69f2445df4f9b17ad2b417be66c3710'
ciphertext = '7649abac8119b246cee98e9b12e9197d' +\
'5086cb9b507219ee95db113a917678b2' +\
'73bed6b8e3c1743b7116e69e22229516' +\
'3ff1caa1681fac09120eca307586e1a7'
key = unhexlify(key)
iv = unhexlify(iv)
plaintext = unhexlify(plaintext)
ciphertext = unhexlify(ciphertext)
cipher = AES.new(key, AES.MODE_CBC, iv)
self.assertEqual(cipher.encrypt(plaintext), ciphertext)
cipher = AES.new(key, AES.MODE_CBC, iv)
self.assertEqual(cipher.decrypt(ciphertext), plaintext)
def test_aes_192(self):
key = '8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b'
iv = '000102030405060708090a0b0c0d0e0f'
plaintext = '6bc1bee22e409f96e93d7e117393172a' +\
'ae2d8a571e03ac9c9eb76fac45af8e51' +\
'30c81c46a35ce411e5fbc1191a0a52ef' +\
'f69f2445df4f9b17ad2b417be66c3710'
ciphertext = '4f021db243bc633d7178183a9fa071e8' +\
'b4d9ada9ad7dedf4e5e738763f69145a' +\
'571b242012fb7ae07fa9baac3df102e0' +\
'08b0e27988598881d920a9e64f5615cd'
key = unhexlify(key)
iv = unhexlify(iv)
plaintext = unhexlify(plaintext)
ciphertext = unhexlify(ciphertext)
cipher = AES.new(key, AES.MODE_CBC, iv)
self.assertEqual(cipher.encrypt(plaintext), ciphertext)
cipher = AES.new(key, AES.MODE_CBC, iv)
self.assertEqual(cipher.decrypt(ciphertext), plaintext)
def test_aes_256(self):
key = '603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4'
iv = '000102030405060708090a0b0c0d0e0f'
plaintext = '6bc1bee22e409f96e93d7e117393172a' +\
'ae2d8a571e03ac9c9eb76fac45af8e51' +\
'30c81c46a35ce411e5fbc1191a0a52ef' +\
'f69f2445df4f9b17ad2b417be66c3710'
ciphertext = 'f58c4c04d6e5f1ba779eabfb5f7bfbd6' +\
'9cfc4e967edb808d679f777bc6702c7d' +\
'39f23369a9d9bacfa530e26304231461' +\
'b2eb05e2c39be9fcda6c19078c6a9d1b'
key = unhexlify(key)
iv = unhexlify(iv)
plaintext = unhexlify(plaintext)
ciphertext = unhexlify(ciphertext)
cipher = AES.new(key, AES.MODE_CBC, iv)
self.assertEqual(cipher.encrypt(plaintext), ciphertext)
cipher = AES.new(key, AES.MODE_CBC, iv)
self.assertEqual(cipher.decrypt(ciphertext), plaintext)
def get_tests(config={}):
tests = []
tests += list_test_cases(CbcTests)
if config.get('slow_tests'):
tests += list_test_cases(NistCbcVectors)
tests += list_test_cases(SP800TestVectors)
return tests
if __name__ == '__main__':
suite = lambda: unittest.TestSuite(get_tests())
unittest.main(defaultTest='suite')
PK ! GvCC C Cipher/common.pynu [ # -*- coding: utf-8 -*-
#
# SelfTest/Hash/common.py: Common code for Crypto.SelfTest.Hash
#
# Written in 2008 by Dwayne C. Litzenberger
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the extent that dedication to the public domain is not available,
# everyone is granted a worldwide, perpetual, royalty-free,
# non-exclusive license to exercise all rights associated with the
# contents of this file for any purpose whatsoever.
# No rights are reserved.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# ===================================================================
"""Self-testing for PyCrypto hash modules"""
import unittest
from binascii import a2b_hex, b2a_hex, hexlify
from Crypto.Util.py3compat import b
from Crypto.Util.strxor import strxor_c
class _NoDefault: pass # sentinel object
def _extract(d, k, default=_NoDefault):
"""Get an item from a dictionary, and remove it from the dictionary."""
try:
retval = d[k]
except KeyError:
if default is _NoDefault:
raise
return default
del d[k]
return retval
# Generic cipher test case
class CipherSelfTest(unittest.TestCase):
def __init__(self, module, params):
unittest.TestCase.__init__(self)
self.module = module
# Extract the parameters
params = params.copy()
self.description = _extract(params, 'description')
self.key = b(_extract(params, 'key'))
self.plaintext = b(_extract(params, 'plaintext'))
self.ciphertext = b(_extract(params, 'ciphertext'))
self.module_name = _extract(params, 'module_name', None)
self.assoc_data = _extract(params, 'assoc_data', None)
self.mac = _extract(params, 'mac', None)
if self.assoc_data:
self.mac = b(self.mac)
mode = _extract(params, 'mode', None)
self.mode_name = str(mode)
if mode is not None:
# Block cipher
self.mode = getattr(self.module, "MODE_" + mode)
self.iv = _extract(params, 'iv', None)
if self.iv is None:
self.iv = _extract(params, 'nonce', None)
if self.iv is not None:
self.iv = b(self.iv)
else:
# Stream cipher
self.mode = None
self.iv = _extract(params, 'iv', None)
if self.iv is not None:
self.iv = b(self.iv)
self.extra_params = params
def shortDescription(self):
return self.description
def _new(self):
params = self.extra_params.copy()
key = a2b_hex(self.key)
old_style = []
if self.mode is not None:
old_style = [ self.mode ]
if self.iv is not None:
old_style += [ a2b_hex(self.iv) ]
return self.module.new(key, *old_style, **params)
def isMode(self, name):
if not hasattr(self.module, "MODE_"+name):
return False
return self.mode == getattr(self.module, "MODE_"+name)
def runTest(self):
plaintext = a2b_hex(self.plaintext)
ciphertext = a2b_hex(self.ciphertext)
assoc_data = []
if self.assoc_data:
assoc_data = [ a2b_hex(b(x)) for x in self.assoc_data]
ct = None
pt = None
#
# Repeat the same encryption or decryption twice and verify
# that the result is always the same
#
for i in range(2):
cipher = self._new()
decipher = self._new()
# Only AEAD modes
for comp in assoc_data:
cipher.update(comp)
decipher.update(comp)
ctX = b2a_hex(cipher.encrypt(plaintext))
ptX = b2a_hex(decipher.decrypt(ciphertext))
if ct:
self.assertEqual(ct, ctX)
self.assertEqual(pt, ptX)
ct, pt = ctX, ptX
self.assertEqual(self.ciphertext, ct) # encrypt
self.assertEqual(self.plaintext, pt) # decrypt
if self.mac:
mac = b2a_hex(cipher.digest())
self.assertEqual(self.mac, mac)
decipher.verify(a2b_hex(self.mac))
class CipherStreamingSelfTest(CipherSelfTest):
def shortDescription(self):
desc = self.module_name
if self.mode is not None:
desc += " in %s mode" % (self.mode_name,)
return "%s should behave like a stream cipher" % (desc,)
def runTest(self):
plaintext = a2b_hex(self.plaintext)
ciphertext = a2b_hex(self.ciphertext)
# The cipher should work like a stream cipher
# Test counter mode encryption, 3 bytes at a time
ct3 = []
cipher = self._new()
for i in range(0, len(plaintext), 3):
ct3.append(cipher.encrypt(plaintext[i:i+3]))
ct3 = b2a_hex(b("").join(ct3))
self.assertEqual(self.ciphertext, ct3) # encryption (3 bytes at a time)
# Test counter mode decryption, 3 bytes at a time
pt3 = []
cipher = self._new()
for i in range(0, len(ciphertext), 3):
pt3.append(cipher.encrypt(ciphertext[i:i+3]))
# PY3K: This is meant to be text, do not change to bytes (data)
pt3 = b2a_hex(b("").join(pt3))
self.assertEqual(self.plaintext, pt3) # decryption (3 bytes at a time)
class RoundtripTest(unittest.TestCase):
def __init__(self, module, params):
from Crypto import Random
unittest.TestCase.__init__(self)
self.module = module
self.iv = Random.get_random_bytes(module.block_size)
self.key = b(params['key'])
self.plaintext = 100 * b(params['plaintext'])
self.module_name = params.get('module_name', None)
def shortDescription(self):
return """%s .decrypt() output of .encrypt() should not be garbled""" % (self.module_name,)
def runTest(self):
## ECB mode
mode = self.module.MODE_ECB
encryption_cipher = self.module.new(a2b_hex(self.key), mode)
ciphertext = encryption_cipher.encrypt(self.plaintext)
decryption_cipher = self.module.new(a2b_hex(self.key), mode)
decrypted_plaintext = decryption_cipher.decrypt(ciphertext)
self.assertEqual(self.plaintext, decrypted_plaintext)
class IVLengthTest(unittest.TestCase):
def __init__(self, module, params):
unittest.TestCase.__init__(self)
self.module = module
self.key = b(params['key'])
def shortDescription(self):
return "Check that all modes except MODE_ECB and MODE_CTR require an IV of the proper length"
def runTest(self):
self.assertRaises(TypeError, self.module.new, a2b_hex(self.key),
self.module.MODE_ECB, b(""))
def _dummy_counter(self):
return "\0" * self.module.block_size
class NoDefaultECBTest(unittest.TestCase):
def __init__(self, module, params):
unittest.TestCase.__init__(self)
self.module = module
self.key = b(params['key'])
def runTest(self):
self.assertRaises(TypeError, self.module.new, a2b_hex(self.key))
class BlockSizeTest(unittest.TestCase):
def __init__(self, module, params):
unittest.TestCase.__init__(self)
self.module = module
self.key = a2b_hex(b(params['key']))
def runTest(self):
cipher = self.module.new(self.key, self.module.MODE_ECB)
self.assertEqual(cipher.block_size, self.module.block_size)
class ByteArrayTest(unittest.TestCase):
"""Verify we can use bytearray's for encrypting and decrypting"""
def __init__(self, module, params):
unittest.TestCase.__init__(self)
self.module = module
# Extract the parameters
params = params.copy()
self.description = _extract(params, 'description')
self.key = b(_extract(params, 'key'))
self.plaintext = b(_extract(params, 'plaintext'))
self.ciphertext = b(_extract(params, 'ciphertext'))
self.module_name = _extract(params, 'module_name', None)
self.assoc_data = _extract(params, 'assoc_data', None)
self.mac = _extract(params, 'mac', None)
if self.assoc_data:
self.mac = b(self.mac)
mode = _extract(params, 'mode', None)
self.mode_name = str(mode)
if mode is not None:
# Block cipher
self.mode = getattr(self.module, "MODE_" + mode)
self.iv = _extract(params, 'iv', None)
if self.iv is None:
self.iv = _extract(params, 'nonce', None)
if self.iv is not None:
self.iv = b(self.iv)
else:
# Stream cipher
self.mode = None
self.iv = _extract(params, 'iv', None)
if self.iv is not None:
self.iv = b(self.iv)
self.extra_params = params
def _new(self):
params = self.extra_params.copy()
key = a2b_hex(self.key)
old_style = []
if self.mode is not None:
old_style = [ self.mode ]
if self.iv is not None:
old_style += [ a2b_hex(self.iv) ]
return self.module.new(key, *old_style, **params)
def runTest(self):
plaintext = a2b_hex(self.plaintext)
ciphertext = a2b_hex(self.ciphertext)
assoc_data = []
if self.assoc_data:
assoc_data = [ bytearray(a2b_hex(b(x))) for x in self.assoc_data]
cipher = self._new()
decipher = self._new()
# Only AEAD modes
for comp in assoc_data:
cipher.update(comp)
decipher.update(comp)
ct = b2a_hex(cipher.encrypt(bytearray(plaintext)))
pt = b2a_hex(decipher.decrypt(bytearray(ciphertext)))
self.assertEqual(self.ciphertext, ct) # encrypt
self.assertEqual(self.plaintext, pt) # decrypt
if self.mac:
mac = b2a_hex(cipher.digest())
self.assertEqual(self.mac, mac)
decipher.verify(bytearray(a2b_hex(self.mac)))
class MemoryviewTest(unittest.TestCase):
"""Verify we can use memoryviews for encrypting and decrypting"""
def __init__(self, module, params):
unittest.TestCase.__init__(self)
self.module = module
# Extract the parameters
params = params.copy()
self.description = _extract(params, 'description')
self.key = b(_extract(params, 'key'))
self.plaintext = b(_extract(params, 'plaintext'))
self.ciphertext = b(_extract(params, 'ciphertext'))
self.module_name = _extract(params, 'module_name', None)
self.assoc_data = _extract(params, 'assoc_data', None)
self.mac = _extract(params, 'mac', None)
if self.assoc_data:
self.mac = b(self.mac)
mode = _extract(params, 'mode', None)
self.mode_name = str(mode)
if mode is not None:
# Block cipher
self.mode = getattr(self.module, "MODE_" + mode)
self.iv = _extract(params, 'iv', None)
if self.iv is None:
self.iv = _extract(params, 'nonce', None)
if self.iv is not None:
self.iv = b(self.iv)
else:
# Stream cipher
self.mode = None
self.iv = _extract(params, 'iv', None)
if self.iv is not None:
self.iv = b(self.iv)
self.extra_params = params
def _new(self):
params = self.extra_params.copy()
key = a2b_hex(self.key)
old_style = []
if self.mode is not None:
old_style = [ self.mode ]
if self.iv is not None:
old_style += [ a2b_hex(self.iv) ]
return self.module.new(key, *old_style, **params)
def runTest(self):
plaintext = a2b_hex(self.plaintext)
ciphertext = a2b_hex(self.ciphertext)
assoc_data = []
if self.assoc_data:
assoc_data = [ memoryview(a2b_hex(b(x))) for x in self.assoc_data]
cipher = self._new()
decipher = self._new()
# Only AEAD modes
for comp in assoc_data:
cipher.update(comp)
decipher.update(comp)
ct = b2a_hex(cipher.encrypt(memoryview(plaintext)))
pt = b2a_hex(decipher.decrypt(memoryview(ciphertext)))
self.assertEqual(self.ciphertext, ct) # encrypt
self.assertEqual(self.plaintext, pt) # decrypt
if self.mac:
mac = b2a_hex(cipher.digest())
self.assertEqual(self.mac, mac)
decipher.verify(memoryview(a2b_hex(self.mac)))
def make_block_tests(module, module_name, test_data, additional_params=dict()):
tests = []
extra_tests_added = False
for i in range(len(test_data)):
row = test_data[i]
# Build the "params" dictionary with
# - plaintext
# - ciphertext
# - key
# - mode (default is ECB)
# - (optionally) description
# - (optionally) any other parameter that this cipher mode requires
params = {}
if len(row) == 3:
(params['plaintext'], params['ciphertext'], params['key']) = row
elif len(row) == 4:
(params['plaintext'], params['ciphertext'], params['key'], params['description']) = row
elif len(row) == 5:
(params['plaintext'], params['ciphertext'], params['key'], params['description'], extra_params) = row
params.update(extra_params)
else:
raise AssertionError("Unsupported tuple size %d" % (len(row),))
if not "mode" in params:
params["mode"] = "ECB"
# Build the display-name for the test
p2 = params.copy()
p_key = _extract(p2, 'key')
p_plaintext = _extract(p2, 'plaintext')
p_ciphertext = _extract(p2, 'ciphertext')
p_mode = _extract(p2, 'mode')
p_description = _extract(p2, 'description', None)
if p_description is not None:
description = p_description
elif p_mode == 'ECB' and not p2:
description = "p=%s, k=%s" % (p_plaintext, p_key)
else:
description = "p=%s, k=%s, %r" % (p_plaintext, p_key, p2)
name = "%s #%d: %s" % (module_name, i+1, description)
params['description'] = name
params['module_name'] = module_name
params.update(additional_params)
# Add extra test(s) to the test suite before the current test
if not extra_tests_added:
tests += [
RoundtripTest(module, params),
IVLengthTest(module, params),
NoDefaultECBTest(module, params),
ByteArrayTest(module, params),
BlockSizeTest(module, params),
]
extra_tests_added = True
# Add the current test to the test suite
tests.append(CipherSelfTest(module, params))
return tests
def make_stream_tests(module, module_name, test_data):
tests = []
extra_tests_added = False
for i in range(len(test_data)):
row = test_data[i]
# Build the "params" dictionary
params = {}
if len(row) == 3:
(params['plaintext'], params['ciphertext'], params['key']) = row
elif len(row) == 4:
(params['plaintext'], params['ciphertext'], params['key'], params['description']) = row
elif len(row) == 5:
(params['plaintext'], params['ciphertext'], params['key'], params['description'], extra_params) = row
params.update(extra_params)
else:
raise AssertionError("Unsupported tuple size %d" % (len(row),))
# Build the display-name for the test
p2 = params.copy()
p_key = _extract(p2, 'key')
p_plaintext = _extract(p2, 'plaintext')
p_ciphertext = _extract(p2, 'ciphertext')
p_description = _extract(p2, 'description', None)
if p_description is not None:
description = p_description
elif not p2:
description = "p=%s, k=%s" % (p_plaintext, p_key)
else:
description = "p=%s, k=%s, %r" % (p_plaintext, p_key, p2)
name = "%s #%d: %s" % (module_name, i+1, description)
params['description'] = name
params['module_name'] = module_name
# Add extra test(s) to the test suite before the current test
if not extra_tests_added:
tests += [
ByteArrayTest(module, params),
]
tests.append(MemoryviewTest(module, params))
extra_tests_added = True
# Add the test to the test suite
tests.append(CipherSelfTest(module, params))
tests.append(CipherStreamingSelfTest(module, params))
return tests
# vim:set ts=4 sw=4 sts=4 expandtab:
PK ! -G> G> Cipher/test_DES.pynu [ # -*- coding: utf-8 -*-
#
# SelfTest/Cipher/DES.py: Self-test for the (Single) DES cipher
#
# Written in 2008 by Dwayne C. Litzenberger
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the extent that dedication to the public domain is not available,
# everyone is granted a worldwide, perpetual, royalty-free,
# non-exclusive license to exercise all rights associated with the
# contents of this file for any purpose whatsoever.
# No rights are reserved.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# ===================================================================
"""Self-test suite for Crypto.Cipher.DES"""
import unittest
from Crypto.Cipher import DES
# This is a list of (plaintext, ciphertext, key, description) tuples.
SP800_17_B1_KEY = '01' * 8
SP800_17_B2_PT = '00' * 8
test_data = [
# Test vectors from Appendix A of NIST SP 800-17
# "Modes of Operation Validation System (MOVS): Requirements and Procedures"
# http://csrc.nist.gov/publications/nistpubs/800-17/800-17.pdf
# Appendix A - "Sample Round Outputs for the DES"
('0000000000000000', '82dcbafbdeab6602', '10316e028c8f3b4a',
"NIST SP800-17 A"),
# Table B.1 - Variable Plaintext Known Answer Test
('8000000000000000', '95f8a5e5dd31d900', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #0'),
('4000000000000000', 'dd7f121ca5015619', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #1'),
('2000000000000000', '2e8653104f3834ea', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #2'),
('1000000000000000', '4bd388ff6cd81d4f', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #3'),
('0800000000000000', '20b9e767b2fb1456', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #4'),
('0400000000000000', '55579380d77138ef', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #5'),
('0200000000000000', '6cc5defaaf04512f', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #6'),
('0100000000000000', '0d9f279ba5d87260', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #7'),
('0080000000000000', 'd9031b0271bd5a0a', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #8'),
('0040000000000000', '424250b37c3dd951', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #9'),
('0020000000000000', 'b8061b7ecd9a21e5', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #10'),
('0010000000000000', 'f15d0f286b65bd28', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #11'),
('0008000000000000', 'add0cc8d6e5deba1', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #12'),
('0004000000000000', 'e6d5f82752ad63d1', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #13'),
('0002000000000000', 'ecbfe3bd3f591a5e', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #14'),
('0001000000000000', 'f356834379d165cd', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #15'),
('0000800000000000', '2b9f982f20037fa9', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #16'),
('0000400000000000', '889de068a16f0be6', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #17'),
('0000200000000000', 'e19e275d846a1298', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #18'),
('0000100000000000', '329a8ed523d71aec', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #19'),
('0000080000000000', 'e7fce22557d23c97', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #20'),
('0000040000000000', '12a9f5817ff2d65d', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #21'),
('0000020000000000', 'a484c3ad38dc9c19', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #22'),
('0000010000000000', 'fbe00a8a1ef8ad72', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #23'),
('0000008000000000', '750d079407521363', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #24'),
('0000004000000000', '64feed9c724c2faf', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #25'),
('0000002000000000', 'f02b263b328e2b60', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #26'),
('0000001000000000', '9d64555a9a10b852', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #27'),
('0000000800000000', 'd106ff0bed5255d7', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #28'),
('0000000400000000', 'e1652c6b138c64a5', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #29'),
('0000000200000000', 'e428581186ec8f46', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #30'),
('0000000100000000', 'aeb5f5ede22d1a36', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #31'),
('0000000080000000', 'e943d7568aec0c5c', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #32'),
('0000000040000000', 'df98c8276f54b04b', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #33'),
('0000000020000000', 'b160e4680f6c696f', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #34'),
('0000000010000000', 'fa0752b07d9c4ab8', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #35'),
('0000000008000000', 'ca3a2b036dbc8502', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #36'),
('0000000004000000', '5e0905517bb59bcf', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #37'),
('0000000002000000', '814eeb3b91d90726', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #38'),
('0000000001000000', '4d49db1532919c9f', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #39'),
('0000000000800000', '25eb5fc3f8cf0621', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #40'),
('0000000000400000', 'ab6a20c0620d1c6f', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #41'),
('0000000000200000', '79e90dbc98f92cca', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #42'),
('0000000000100000', '866ecedd8072bb0e', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #43'),
('0000000000080000', '8b54536f2f3e64a8', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #44'),
('0000000000040000', 'ea51d3975595b86b', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #45'),
('0000000000020000', 'caffc6ac4542de31', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #46'),
('0000000000010000', '8dd45a2ddf90796c', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #47'),
('0000000000008000', '1029d55e880ec2d0', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #48'),
('0000000000004000', '5d86cb23639dbea9', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #49'),
('0000000000002000', '1d1ca853ae7c0c5f', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #50'),
('0000000000001000', 'ce332329248f3228', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #51'),
('0000000000000800', '8405d1abe24fb942', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #52'),
('0000000000000400', 'e643d78090ca4207', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #53'),
('0000000000000200', '48221b9937748a23', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #54'),
('0000000000000100', 'dd7c0bbd61fafd54', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #55'),
('0000000000000080', '2fbc291a570db5c4', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #56'),
('0000000000000040', 'e07c30d7e4e26e12', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #57'),
('0000000000000020', '0953e2258e8e90a1', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #58'),
('0000000000000010', '5b711bc4ceebf2ee', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #59'),
('0000000000000008', 'cc083f1e6d9e85f6', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #60'),
('0000000000000004', 'd2fd8867d50d2dfe', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #61'),
('0000000000000002', '06e7ea22ce92708f', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #62'),
('0000000000000001', '166b40b44aba4bd6', SP800_17_B1_KEY,
'NIST SP800-17 B.1 #63'),
# Table B.2 - Variable Key Known Answer Test
(SP800_17_B2_PT, '95a8d72813daa94d', '8001010101010101',
'NIST SP800-17 B.2 #0'),
(SP800_17_B2_PT, '0eec1487dd8c26d5', '4001010101010101',
'NIST SP800-17 B.2 #1'),
(SP800_17_B2_PT, '7ad16ffb79c45926', '2001010101010101',
'NIST SP800-17 B.2 #2'),
(SP800_17_B2_PT, 'd3746294ca6a6cf3', '1001010101010101',
'NIST SP800-17 B.2 #3'),
(SP800_17_B2_PT, '809f5f873c1fd761', '0801010101010101',
'NIST SP800-17 B.2 #4'),
(SP800_17_B2_PT, 'c02faffec989d1fc', '0401010101010101',
'NIST SP800-17 B.2 #5'),
(SP800_17_B2_PT, '4615aa1d33e72f10', '0201010101010101',
'NIST SP800-17 B.2 #6'),
(SP800_17_B2_PT, '2055123350c00858', '0180010101010101',
'NIST SP800-17 B.2 #7'),
(SP800_17_B2_PT, 'df3b99d6577397c8', '0140010101010101',
'NIST SP800-17 B.2 #8'),
(SP800_17_B2_PT, '31fe17369b5288c9', '0120010101010101',
'NIST SP800-17 B.2 #9'),
(SP800_17_B2_PT, 'dfdd3cc64dae1642', '0110010101010101',
'NIST SP800-17 B.2 #10'),
(SP800_17_B2_PT, '178c83ce2b399d94', '0108010101010101',
'NIST SP800-17 B.2 #11'),
(SP800_17_B2_PT, '50f636324a9b7f80', '0104010101010101',
'NIST SP800-17 B.2 #12'),
(SP800_17_B2_PT, 'a8468ee3bc18f06d', '0102010101010101',
'NIST SP800-17 B.2 #13'),
(SP800_17_B2_PT, 'a2dc9e92fd3cde92', '0101800101010101',
'NIST SP800-17 B.2 #14'),
(SP800_17_B2_PT, 'cac09f797d031287', '0101400101010101',
'NIST SP800-17 B.2 #15'),
(SP800_17_B2_PT, '90ba680b22aeb525', '0101200101010101',
'NIST SP800-17 B.2 #16'),
(SP800_17_B2_PT, 'ce7a24f350e280b6', '0101100101010101',
'NIST SP800-17 B.2 #17'),
(SP800_17_B2_PT, '882bff0aa01a0b87', '0101080101010101',
'NIST SP800-17 B.2 #18'),
(SP800_17_B2_PT, '25610288924511c2', '0101040101010101',
'NIST SP800-17 B.2 #19'),
(SP800_17_B2_PT, 'c71516c29c75d170', '0101020101010101',
'NIST SP800-17 B.2 #20'),
(SP800_17_B2_PT, '5199c29a52c9f059', '0101018001010101',
'NIST SP800-17 B.2 #21'),
(SP800_17_B2_PT, 'c22f0a294a71f29f', '0101014001010101',
'NIST SP800-17 B.2 #22'),
(SP800_17_B2_PT, 'ee371483714c02ea', '0101012001010101',
'NIST SP800-17 B.2 #23'),
(SP800_17_B2_PT, 'a81fbd448f9e522f', '0101011001010101',
'NIST SP800-17 B.2 #24'),
(SP800_17_B2_PT, '4f644c92e192dfed', '0101010801010101',
'NIST SP800-17 B.2 #25'),
(SP800_17_B2_PT, '1afa9a66a6df92ae', '0101010401010101',
'NIST SP800-17 B.2 #26'),
(SP800_17_B2_PT, 'b3c1cc715cb879d8', '0101010201010101',
'NIST SP800-17 B.2 #27'),
(SP800_17_B2_PT, '19d032e64ab0bd8b', '0101010180010101',
'NIST SP800-17 B.2 #28'),
(SP800_17_B2_PT, '3cfaa7a7dc8720dc', '0101010140010101',
'NIST SP800-17 B.2 #29'),
(SP800_17_B2_PT, 'b7265f7f447ac6f3', '0101010120010101',
'NIST SP800-17 B.2 #30'),
(SP800_17_B2_PT, '9db73b3c0d163f54', '0101010110010101',
'NIST SP800-17 B.2 #31'),
(SP800_17_B2_PT, '8181b65babf4a975', '0101010108010101',
'NIST SP800-17 B.2 #32'),
(SP800_17_B2_PT, '93c9b64042eaa240', '0101010104010101',
'NIST SP800-17 B.2 #33'),
(SP800_17_B2_PT, '5570530829705592', '0101010102010101',
'NIST SP800-17 B.2 #34'),
(SP800_17_B2_PT, '8638809e878787a0', '0101010101800101',
'NIST SP800-17 B.2 #35'),
(SP800_17_B2_PT, '41b9a79af79ac208', '0101010101400101',
'NIST SP800-17 B.2 #36'),
(SP800_17_B2_PT, '7a9be42f2009a892', '0101010101200101',
'NIST SP800-17 B.2 #37'),
(SP800_17_B2_PT, '29038d56ba6d2745', '0101010101100101',
'NIST SP800-17 B.2 #38'),
(SP800_17_B2_PT, '5495c6abf1e5df51', '0101010101080101',
'NIST SP800-17 B.2 #39'),
(SP800_17_B2_PT, 'ae13dbd561488933', '0101010101040101',
'NIST SP800-17 B.2 #40'),
(SP800_17_B2_PT, '024d1ffa8904e389', '0101010101020101',
'NIST SP800-17 B.2 #41'),
(SP800_17_B2_PT, 'd1399712f99bf02e', '0101010101018001',
'NIST SP800-17 B.2 #42'),
(SP800_17_B2_PT, '14c1d7c1cffec79e', '0101010101014001',
'NIST SP800-17 B.2 #43'),
(SP800_17_B2_PT, '1de5279dae3bed6f', '0101010101012001',
'NIST SP800-17 B.2 #44'),
(SP800_17_B2_PT, 'e941a33f85501303', '0101010101011001',
'NIST SP800-17 B.2 #45'),
(SP800_17_B2_PT, 'da99dbbc9a03f379', '0101010101010801',
'NIST SP800-17 B.2 #46'),
(SP800_17_B2_PT, 'b7fc92f91d8e92e9', '0101010101010401',
'NIST SP800-17 B.2 #47'),
(SP800_17_B2_PT, 'ae8e5caa3ca04e85', '0101010101010201',
'NIST SP800-17 B.2 #48'),
(SP800_17_B2_PT, '9cc62df43b6eed74', '0101010101010180',
'NIST SP800-17 B.2 #49'),
(SP800_17_B2_PT, 'd863dbb5c59a91a0', '0101010101010140',
'NIST SP800-17 B.2 #50'),
(SP800_17_B2_PT, 'a1ab2190545b91d7', '0101010101010120',
'NIST SP800-17 B.2 #51'),
(SP800_17_B2_PT, '0875041e64c570f7', '0101010101010110',
'NIST SP800-17 B.2 #52'),
(SP800_17_B2_PT, '5a594528bebef1cc', '0101010101010108',
'NIST SP800-17 B.2 #53'),
(SP800_17_B2_PT, 'fcdb3291de21f0c0', '0101010101010104',
'NIST SP800-17 B.2 #54'),
(SP800_17_B2_PT, '869efd7f9f265a09', '0101010101010102',
'NIST SP800-17 B.2 #55'),
]
class RonRivestTest(unittest.TestCase):
""" Ronald L. Rivest's DES test, see
http://people.csail.mit.edu/rivest/Destest.txt
ABSTRACT
--------
We present a simple way to test the correctness of a DES implementation:
Use the recurrence relation:
X0 = 9474B8E8C73BCA7D (hexadecimal)
X(i+1) = IF (i is even) THEN E(Xi,Xi) ELSE D(Xi,Xi)
to compute a sequence of 64-bit values: X0, X1, X2, ..., X16. Here
E(X,K) denotes the DES encryption of X using key K, and D(X,K) denotes
the DES decryption of X using key K. If you obtain
X16 = 1B1A2DDB4C642438
your implementation does not have any of the 36,568 possible single-fault
errors described herein.
"""
def runTest(self):
from binascii import b2a_hex
X = []
X[0:] = [b'\x94\x74\xB8\xE8\xC7\x3B\xCA\x7D']
for i in range(16):
c = DES.new(X[i],DES.MODE_ECB)
if not (i&1): # (num&1) returns 1 for odd numbers
X[i+1:] = [c.encrypt(X[i])] # even
else:
X[i+1:] = [c.decrypt(X[i])] # odd
self.assertEqual(b2a_hex(X[16]),
b2a_hex(b'\x1B\x1A\x2D\xDB\x4C\x64\x24\x38'))
class TestOutput(unittest.TestCase):
def runTest(self):
# Encrypt/Decrypt data and test output parameter
cipher = DES.new(b'4'*8, DES.MODE_ECB)
pt = b'5' * 8
ct = cipher.encrypt(pt)
output = bytearray(8)
res = cipher.encrypt(pt, output=output)
self.assertEqual(ct, output)
self.assertEqual(res, None)
res = cipher.decrypt(ct, output=output)
self.assertEqual(pt, output)
self.assertEqual(res, None)
output = memoryview(bytearray(8))
cipher.encrypt(pt, output=output)
self.assertEqual(ct, output)
cipher.decrypt(ct, output=output)
self.assertEqual(pt, output)
self.assertRaises(TypeError, cipher.encrypt, pt, output=b'0'*8)
self.assertRaises(TypeError, cipher.decrypt, ct, output=b'0'*8)
shorter_output = bytearray(7)
self.assertRaises(ValueError, cipher.encrypt, pt, output=shorter_output)
self.assertRaises(ValueError, cipher.decrypt, ct, output=shorter_output)
def get_tests(config={}):
from .common import make_block_tests
tests = make_block_tests(DES, "DES", test_data)
tests += [RonRivestTest()]
tests += [TestOutput()]
return tests
if __name__ == '__main__':
import unittest
suite = lambda: unittest.TestSuite(get_tests())
unittest.main(defaultTest='suite')
# vim:set ts=4 sw=4 sts=4 expandtab:
PK ! S Cipher/test_GCM.pynu [ # ===================================================================
#
# Copyright (c) 2015, Legrandin
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ===================================================================
from __future__ import print_function
import unittest
from binascii import unhexlify
from Crypto.SelfTest.st_common import list_test_cases
from Crypto.SelfTest.loader import load_test_vectors, load_test_vectors_wycheproof
from Crypto.Util.py3compat import tobytes, bchr
from Crypto.Cipher import AES
from Crypto.Hash import SHAKE128, SHA256
from Crypto.Util.strxor import strxor
def get_tag_random(tag, length):
return SHAKE128.new(data=tobytes(tag)).read(length)
class GcmTests(unittest.TestCase):
key_128 = get_tag_random("key_128", 16)
nonce_96 = get_tag_random("nonce_128", 12)
data = get_tag_random("data", 128)
def test_loopback_128(self):
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
pt = get_tag_random("plaintext", 16 * 100)
ct = cipher.encrypt(pt)
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
pt2 = cipher.decrypt(ct)
self.assertEqual(pt, pt2)
def test_nonce(self):
# Nonce is optional (a random one will be created)
AES.new(self.key_128, AES.MODE_GCM)
cipher = AES.new(self.key_128, AES.MODE_GCM, self.nonce_96)
ct = cipher.encrypt(self.data)
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
self.assertEqual(ct, cipher.encrypt(self.data))
def test_nonce_must_be_bytes(self):
self.assertRaises(TypeError, AES.new, self.key_128, AES.MODE_GCM,
nonce=u'test12345678')
def test_nonce_length(self):
# nonce can be of any length (but not empty)
self.assertRaises(ValueError, AES.new, self.key_128, AES.MODE_GCM,
nonce=b"")
for x in range(1, 128):
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=bchr(1) * x)
cipher.encrypt(bchr(1))
def test_block_size_128(self):
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
self.assertEqual(cipher.block_size, AES.block_size)
def test_nonce_attribute(self):
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
self.assertEqual(cipher.nonce, self.nonce_96)
# By default, a 15 bytes long nonce is randomly generated
nonce1 = AES.new(self.key_128, AES.MODE_GCM).nonce
nonce2 = AES.new(self.key_128, AES.MODE_GCM).nonce
self.assertEqual(len(nonce1), 16)
self.assertNotEqual(nonce1, nonce2)
def test_unknown_parameters(self):
self.assertRaises(TypeError, AES.new, self.key_128, AES.MODE_GCM,
self.nonce_96, 7)
self.assertRaises(TypeError, AES.new, self.key_128, AES.MODE_GCM,
nonce=self.nonce_96, unknown=7)
# But some are only known by the base cipher
# (e.g. use_aesni consumed by the AES module)
AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96,
use_aesni=False)
def test_null_encryption_decryption(self):
for func in "encrypt", "decrypt":
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
result = getattr(cipher, func)(b"")
self.assertEqual(result, b"")
def test_either_encrypt_or_decrypt(self):
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
cipher.encrypt(b"")
self.assertRaises(TypeError, cipher.decrypt, b"")
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
cipher.decrypt(b"")
self.assertRaises(TypeError, cipher.encrypt, b"")
def test_data_must_be_bytes(self):
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
self.assertRaises(TypeError, cipher.encrypt, u'test1234567890-*')
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
self.assertRaises(TypeError, cipher.decrypt, u'test1234567890-*')
def test_mac_len(self):
# Invalid MAC length
self.assertRaises(ValueError, AES.new, self.key_128, AES.MODE_GCM,
nonce=self.nonce_96, mac_len=3)
self.assertRaises(ValueError, AES.new, self.key_128, AES.MODE_GCM,
nonce=self.nonce_96, mac_len=16+1)
# Valid MAC length
for mac_len in range(5, 16 + 1):
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96,
mac_len=mac_len)
_, mac = cipher.encrypt_and_digest(self.data)
self.assertEqual(len(mac), mac_len)
# Default MAC length
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
_, mac = cipher.encrypt_and_digest(self.data)
self.assertEqual(len(mac), 16)
def test_invalid_mac(self):
from Crypto.Util.strxor import strxor_c
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
ct, mac = cipher.encrypt_and_digest(self.data)
invalid_mac = strxor_c(mac, 0x01)
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
self.assertRaises(ValueError, cipher.decrypt_and_verify, ct,
invalid_mac)
def test_hex_mac(self):
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
mac_hex = cipher.hexdigest()
self.assertEqual(cipher.digest(), unhexlify(mac_hex))
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
cipher.hexverify(mac_hex)
def test_message_chunks(self):
# Validate that both associated data and plaintext/ciphertext
# can be broken up in chunks of arbitrary length
auth_data = get_tag_random("authenticated data", 127)
plaintext = get_tag_random("plaintext", 127)
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
cipher.update(auth_data)
ciphertext, ref_mac = cipher.encrypt_and_digest(plaintext)
def break_up(data, chunk_length):
return [data[i:i+chunk_length] for i in range(0, len(data),
chunk_length)]
# Encryption
for chunk_length in 1, 2, 3, 7, 10, 13, 16, 40, 80, 128:
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
for chunk in break_up(auth_data, chunk_length):
cipher.update(chunk)
pt2 = b""
for chunk in break_up(ciphertext, chunk_length):
pt2 += cipher.decrypt(chunk)
self.assertEqual(plaintext, pt2)
cipher.verify(ref_mac)
# Decryption
for chunk_length in 1, 2, 3, 7, 10, 13, 16, 40, 80, 128:
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
for chunk in break_up(auth_data, chunk_length):
cipher.update(chunk)
ct2 = b""
for chunk in break_up(plaintext, chunk_length):
ct2 += cipher.encrypt(chunk)
self.assertEqual(ciphertext, ct2)
self.assertEqual(cipher.digest(), ref_mac)
def test_bytearray(self):
# Encrypt
key_ba = bytearray(self.key_128)
nonce_ba = bytearray(self.nonce_96)
header_ba = bytearray(self.data)
data_ba = bytearray(self.data)
cipher1 = AES.new(self.key_128,
AES.MODE_GCM,
nonce=self.nonce_96)
cipher1.update(self.data)
ct = cipher1.encrypt(self.data)
tag = cipher1.digest()
cipher2 = AES.new(key_ba,
AES.MODE_GCM,
nonce=nonce_ba)
key_ba[:3] = b"\xFF\xFF\xFF"
nonce_ba[:3] = b"\xFF\xFF\xFF"
cipher2.update(header_ba)
header_ba[:3] = b"\xFF\xFF\xFF"
ct_test = cipher2.encrypt(data_ba)
data_ba[:3] = b"\xFF\xFF\xFF"
tag_test = cipher2.digest()
self.assertEqual(ct, ct_test)
self.assertEqual(tag, tag_test)
self.assertEqual(cipher1.nonce, cipher2.nonce)
# Decrypt
key_ba = bytearray(self.key_128)
nonce_ba = bytearray(self.nonce_96)
header_ba = bytearray(self.data)
del data_ba
cipher4 = AES.new(key_ba,
AES.MODE_GCM,
nonce=nonce_ba)
key_ba[:3] = b"\xFF\xFF\xFF"
nonce_ba[:3] = b"\xFF\xFF\xFF"
cipher4.update(header_ba)
header_ba[:3] = b"\xFF\xFF\xFF"
pt_test = cipher4.decrypt_and_verify(bytearray(ct_test), bytearray(tag_test))
self.assertEqual(self.data, pt_test)
def test_memoryview(self):
# Encrypt
key_mv = memoryview(bytearray(self.key_128))
nonce_mv = memoryview(bytearray(self.nonce_96))
header_mv = memoryview(bytearray(self.data))
data_mv = memoryview(bytearray(self.data))
cipher1 = AES.new(self.key_128,
AES.MODE_GCM,
nonce=self.nonce_96)
cipher1.update(self.data)
ct = cipher1.encrypt(self.data)
tag = cipher1.digest()
cipher2 = AES.new(key_mv,
AES.MODE_GCM,
nonce=nonce_mv)
key_mv[:3] = b"\xFF\xFF\xFF"
nonce_mv[:3] = b"\xFF\xFF\xFF"
cipher2.update(header_mv)
header_mv[:3] = b"\xFF\xFF\xFF"
ct_test = cipher2.encrypt(data_mv)
data_mv[:3] = b"\xFF\xFF\xFF"
tag_test = cipher2.digest()
self.assertEqual(ct, ct_test)
self.assertEqual(tag, tag_test)
self.assertEqual(cipher1.nonce, cipher2.nonce)
# Decrypt
key_mv = memoryview(bytearray(self.key_128))
nonce_mv = memoryview(bytearray(self.nonce_96))
header_mv = memoryview(bytearray(self.data))
del data_mv
cipher4 = AES.new(key_mv,
AES.MODE_GCM,
nonce=nonce_mv)
key_mv[:3] = b"\xFF\xFF\xFF"
nonce_mv[:3] = b"\xFF\xFF\xFF"
cipher4.update(header_mv)
header_mv[:3] = b"\xFF\xFF\xFF"
pt_test = cipher4.decrypt_and_verify(memoryview(ct_test), memoryview(tag_test))
self.assertEqual(self.data, pt_test)
def test_output_param(self):
pt = b'5' * 128
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
ct = cipher.encrypt(pt)
tag = cipher.digest()
output = bytearray(128)
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
res = cipher.encrypt(pt, output=output)
self.assertEqual(ct, output)
self.assertEqual(res, None)
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
res = cipher.decrypt(ct, output=output)
self.assertEqual(pt, output)
self.assertEqual(res, None)
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
res, tag_out = cipher.encrypt_and_digest(pt, output=output)
self.assertEqual(ct, output)
self.assertEqual(res, None)
self.assertEqual(tag, tag_out)
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
res = cipher.decrypt_and_verify(ct, tag, output=output)
self.assertEqual(pt, output)
self.assertEqual(res, None)
def test_output_param_memoryview(self):
pt = b'5' * 128
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
ct = cipher.encrypt(pt)
output = memoryview(bytearray(128))
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
cipher.encrypt(pt, output=output)
self.assertEqual(ct, output)
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
cipher.decrypt(ct, output=output)
self.assertEqual(pt, output)
def test_output_param_neg(self):
LEN_PT = 128
pt = b'5' * LEN_PT
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
ct = cipher.encrypt(pt)
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
self.assertRaises(TypeError, cipher.encrypt, pt, output=b'0' * LEN_PT)
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
self.assertRaises(TypeError, cipher.decrypt, ct, output=b'0' * LEN_PT)
shorter_output = bytearray(LEN_PT - 1)
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
self.assertRaises(ValueError, cipher.encrypt, pt, output=shorter_output)
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
self.assertRaises(ValueError, cipher.decrypt, ct, output=shorter_output)
class GcmFSMTests(unittest.TestCase):
key_128 = get_tag_random("key_128", 16)
nonce_96 = get_tag_random("nonce_128", 12)
data = get_tag_random("data", 128)
def test_valid_init_encrypt_decrypt_digest_verify(self):
# No authenticated data, fixed plaintext
# Verify path INIT->ENCRYPT->DIGEST
cipher = AES.new(self.key_128, AES.MODE_GCM,
nonce=self.nonce_96)
ct = cipher.encrypt(self.data)
mac = cipher.digest()
# Verify path INIT->DECRYPT->VERIFY
cipher = AES.new(self.key_128, AES.MODE_GCM,
nonce=self.nonce_96)
cipher.decrypt(ct)
cipher.verify(mac)
def test_valid_init_update_digest_verify(self):
# No plaintext, fixed authenticated data
# Verify path INIT->UPDATE->DIGEST
cipher = AES.new(self.key_128, AES.MODE_GCM,
nonce=self.nonce_96)
cipher.update(self.data)
mac = cipher.digest()
# Verify path INIT->UPDATE->VERIFY
cipher = AES.new(self.key_128, AES.MODE_GCM,
nonce=self.nonce_96)
cipher.update(self.data)
cipher.verify(mac)
def test_valid_full_path(self):
# Fixed authenticated data, fixed plaintext
# Verify path INIT->UPDATE->ENCRYPT->DIGEST
cipher = AES.new(self.key_128, AES.MODE_GCM,
nonce=self.nonce_96)
cipher.update(self.data)
ct = cipher.encrypt(self.data)
mac = cipher.digest()
# Verify path INIT->UPDATE->DECRYPT->VERIFY
cipher = AES.new(self.key_128, AES.MODE_GCM,
nonce=self.nonce_96)
cipher.update(self.data)
cipher.decrypt(ct)
cipher.verify(mac)
def test_valid_init_digest(self):
# Verify path INIT->DIGEST
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
cipher.digest()
def test_valid_init_verify(self):
# Verify path INIT->VERIFY
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
mac = cipher.digest()
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
cipher.verify(mac)
def test_valid_multiple_encrypt_or_decrypt(self):
for method_name in "encrypt", "decrypt":
for auth_data in (None, b"333", self.data,
self.data + b"3"):
if auth_data is None:
assoc_len = None
else:
assoc_len = len(auth_data)
cipher = AES.new(self.key_128, AES.MODE_GCM,
nonce=self.nonce_96)
if auth_data is not None:
cipher.update(auth_data)
method = getattr(cipher, method_name)
method(self.data)
method(self.data)
method(self.data)
method(self.data)
def test_valid_multiple_digest_or_verify(self):
# Multiple calls to digest
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
cipher.update(self.data)
first_mac = cipher.digest()
for x in range(4):
self.assertEqual(first_mac, cipher.digest())
# Multiple calls to verify
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
cipher.update(self.data)
for x in range(5):
cipher.verify(first_mac)
def test_valid_encrypt_and_digest_decrypt_and_verify(self):
# encrypt_and_digest
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
cipher.update(self.data)
ct, mac = cipher.encrypt_and_digest(self.data)
# decrypt_and_verify
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
cipher.update(self.data)
pt = cipher.decrypt_and_verify(ct, mac)
self.assertEqual(self.data, pt)
def test_invalid_mixing_encrypt_decrypt(self):
# Once per method, with or without assoc. data
for method1_name, method2_name in (("encrypt", "decrypt"),
("decrypt", "encrypt")):
for assoc_data_present in (True, False):
cipher = AES.new(self.key_128, AES.MODE_GCM,
nonce=self.nonce_96)
if assoc_data_present:
cipher.update(self.data)
getattr(cipher, method1_name)(self.data)
self.assertRaises(TypeError, getattr(cipher, method2_name),
self.data)
def test_invalid_encrypt_or_update_after_digest(self):
for method_name in "encrypt", "update":
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
cipher.encrypt(self.data)
cipher.digest()
self.assertRaises(TypeError, getattr(cipher, method_name),
self.data)
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
cipher.encrypt_and_digest(self.data)
def test_invalid_decrypt_or_update_after_verify(self):
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
ct = cipher.encrypt(self.data)
mac = cipher.digest()
for method_name in "decrypt", "update":
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
cipher.decrypt(ct)
cipher.verify(mac)
self.assertRaises(TypeError, getattr(cipher, method_name),
self.data)
cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
cipher.decrypt_and_verify(ct, mac)
self.assertRaises(TypeError, getattr(cipher, method_name),
self.data)
class TestVectors(unittest.TestCase):
"""Class exercising the GCM test vectors found in
http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/gcm/gcm-revised-spec.pdf"""
# List of test vectors, each made up of:
# - authenticated data
# - plaintext
# - ciphertext
# - MAC
# - AES key
# - nonce
test_vectors_hex = [
(
'',
'',
'',
'58e2fccefa7e3061367f1d57a4e7455a',
'00000000000000000000000000000000',
'000000000000000000000000'
),
(
'',
'00000000000000000000000000000000',
'0388dace60b6a392f328c2b971b2fe78',
'ab6e47d42cec13bdf53a67b21257bddf',
'00000000000000000000000000000000',
'000000000000000000000000'
),
(
'',
'd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72' +
'1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b391aafd255',
'42831ec2217774244b7221b784d0d49ce3aa212f2c02a4e035c17e2329aca12e' +
'21d514b25466931c7d8f6a5aac84aa051ba30b396a0aac973d58e091473f5985',
'4d5c2af327cd64a62cf35abd2ba6fab4',
'feffe9928665731c6d6a8f9467308308',
'cafebabefacedbaddecaf888'
),
(
'feedfacedeadbeeffeedfacedeadbeefabaddad2',
'd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72' +
'1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39',
'42831ec2217774244b7221b784d0d49ce3aa212f2c02a4e035c17e2329aca12e' +
'21d514b25466931c7d8f6a5aac84aa051ba30b396a0aac973d58e091',
'5bc94fbc3221a5db94fae95ae7121a47',
'feffe9928665731c6d6a8f9467308308',
'cafebabefacedbaddecaf888'
),
(
'feedfacedeadbeeffeedfacedeadbeefabaddad2',
'd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72' +
'1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39',
'61353b4c2806934a777ff51fa22a4755699b2a714fcdc6f83766e5f97b6c7423' +
'73806900e49f24b22b097544d4896b424989b5e1ebac0f07c23f4598',
'3612d2e79e3b0785561be14aaca2fccb',
'feffe9928665731c6d6a8f9467308308',
'cafebabefacedbad'
),
(
'feedfacedeadbeeffeedfacedeadbeefabaddad2',
'd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72' +
'1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39',
'8ce24998625615b603a033aca13fb894be9112a5c3a211a8ba262a3cca7e2ca7' +
'01e4a9a4fba43c90ccdcb281d48c7c6fd62875d2aca417034c34aee5',
'619cc5aefffe0bfa462af43c1699d050',
'feffe9928665731c6d6a8f9467308308',
'9313225df88406e555909c5aff5269aa' +
'6a7a9538534f7da1e4c303d2a318a728c3c0c95156809539fcf0e2429a6b5254' +
'16aedbf5a0de6a57a637b39b'
),
(
'',
'',
'',
'cd33b28ac773f74ba00ed1f312572435',
'000000000000000000000000000000000000000000000000',
'000000000000000000000000'
),
(
'',
'00000000000000000000000000000000',
'98e7247c07f0fe411c267e4384b0f600',
'2ff58d80033927ab8ef4d4587514f0fb',
'000000000000000000000000000000000000000000000000',
'000000000000000000000000'
),
(
'',
'd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72' +
'1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b391aafd255',
'3980ca0b3c00e841eb06fac4872a2757859e1ceaa6efd984628593b40ca1e19c' +
'7d773d00c144c525ac619d18c84a3f4718e2448b2fe324d9ccda2710acade256',
'9924a7c8587336bfb118024db8674a14',
'feffe9928665731c6d6a8f9467308308feffe9928665731c',
'cafebabefacedbaddecaf888'
),
(
'feedfacedeadbeeffeedfacedeadbeefabaddad2',
'd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72' +
'1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39',
'3980ca0b3c00e841eb06fac4872a2757859e1ceaa6efd984628593b40ca1e19c' +
'7d773d00c144c525ac619d18c84a3f4718e2448b2fe324d9ccda2710',
'2519498e80f1478f37ba55bd6d27618c',
'feffe9928665731c6d6a8f9467308308feffe9928665731c',
'cafebabefacedbaddecaf888'
),
(
'feedfacedeadbeeffeedfacedeadbeefabaddad2',
'd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72' +
'1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39',
'0f10f599ae14a154ed24b36e25324db8c566632ef2bbb34f8347280fc4507057' +
'fddc29df9a471f75c66541d4d4dad1c9e93a19a58e8b473fa0f062f7',
'65dcc57fcf623a24094fcca40d3533f8',
'feffe9928665731c6d6a8f9467308308feffe9928665731c',
'cafebabefacedbad'
),
(
'feedfacedeadbeeffeedfacedeadbeefabaddad2',
'd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72' +
'1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39',
'd27e88681ce3243c4830165a8fdcf9ff1de9a1d8e6b447ef6ef7b79828666e45' +
'81e79012af34ddd9e2f037589b292db3e67c036745fa22e7e9b7373b',
'dcf566ff291c25bbb8568fc3d376a6d9',
'feffe9928665731c6d6a8f9467308308feffe9928665731c',
'9313225df88406e555909c5aff5269aa' +
'6a7a9538534f7da1e4c303d2a318a728c3c0c95156809539fcf0e2429a6b5254' +
'16aedbf5a0de6a57a637b39b'
),
(
'',
'',
'',
'530f8afbc74536b9a963b4f1c4cb738b',
'0000000000000000000000000000000000000000000000000000000000000000',
'000000000000000000000000'
),
(
'',
'00000000000000000000000000000000',
'cea7403d4d606b6e074ec5d3baf39d18',
'd0d1c8a799996bf0265b98b5d48ab919',
'0000000000000000000000000000000000000000000000000000000000000000',
'000000000000000000000000'
),
( '',
'd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72' +
'1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b391aafd255',
'522dc1f099567d07f47f37a32a84427d643a8cdcbfe5c0c97598a2bd2555d1aa' +
'8cb08e48590dbb3da7b08b1056828838c5f61e6393ba7a0abcc9f662898015ad',
'b094dac5d93471bdec1a502270e3cc6c',
'feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308',
'cafebabefacedbaddecaf888'
),
(
'feedfacedeadbeeffeedfacedeadbeefabaddad2',
'd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72' +
'1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39',
'522dc1f099567d07f47f37a32a84427d643a8cdcbfe5c0c97598a2bd2555d1aa' +
'8cb08e48590dbb3da7b08b1056828838c5f61e6393ba7a0abcc9f662',
'76fc6ece0f4e1768cddf8853bb2d551b',
'feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308',
'cafebabefacedbaddecaf888'
),
(
'feedfacedeadbeeffeedfacedeadbeefabaddad2',
'd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72' +
'1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39',
'c3762df1ca787d32ae47c13bf19844cbaf1ae14d0b976afac52ff7d79bba9de0' +
'feb582d33934a4f0954cc2363bc73f7862ac430e64abe499f47c9b1f',
'3a337dbf46a792c45e454913fe2ea8f2',
'feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308',
'cafebabefacedbad'
),
(
'feedfacedeadbeeffeedfacedeadbeefabaddad2',
'd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72' +
'1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39',
'5a8def2f0c9e53f1f75d7853659e2a20eeb2b22aafde6419a058ab4f6f746bf4' +
'0fc0c3b780f244452da3ebf1c5d82cdea2418997200ef82e44ae7e3f',
'a44a8266ee1c8eb0c8b5d4cf5ae9f19a',
'feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308',
'9313225df88406e555909c5aff5269aa' +
'6a7a9538534f7da1e4c303d2a318a728c3c0c95156809539fcf0e2429a6b5254' +
'16aedbf5a0de6a57a637b39b'
)
]
test_vectors = [[unhexlify(x) for x in tv] for tv in test_vectors_hex]
def runTest(self):
for assoc_data, pt, ct, mac, key, nonce in self.test_vectors:
# Encrypt
cipher = AES.new(key, AES.MODE_GCM, nonce, mac_len=len(mac))
cipher.update(assoc_data)
ct2, mac2 = cipher.encrypt_and_digest(pt)
self.assertEqual(ct, ct2)
self.assertEqual(mac, mac2)
# Decrypt
cipher = AES.new(key, AES.MODE_GCM, nonce, mac_len=len(mac))
cipher.update(assoc_data)
pt2 = cipher.decrypt_and_verify(ct, mac)
self.assertEqual(pt, pt2)
class TestVectorsGueronKrasnov(unittest.TestCase):
"""Class exercising the GCM test vectors found in
'The fragility of AES-GCM authentication algorithm', Gueron, Krasnov
https://eprint.iacr.org/2013/157.pdf"""
def test_1(self):
key = unhexlify("3da6c536d6295579c0959a7043efb503")
iv = unhexlify("2b926197d34e091ef722db94")
aad = unhexlify("00000000000000000000000000000000" +
"000102030405060708090a0b0c0d0e0f" +
"101112131415161718191a1b1c1d1e1f" +
"202122232425262728292a2b2c2d2e2f" +
"303132333435363738393a3b3c3d3e3f")
digest = unhexlify("69dd586555ce3fcc89663801a71d957b")
cipher = AES.new(key, AES.MODE_GCM, iv).update(aad)
self.assertEqual(digest, cipher.digest())
def test_2(self):
key = unhexlify("843ffcf5d2b72694d19ed01d01249412")
iv = unhexlify("dbcca32ebf9b804617c3aa9e")
aad = unhexlify("00000000000000000000000000000000" +
"101112131415161718191a1b1c1d1e1f")
pt = unhexlify("000102030405060708090a0b0c0d0e0f" +
"101112131415161718191a1b1c1d1e1f" +
"202122232425262728292a2b2c2d2e2f" +
"303132333435363738393a3b3c3d3e3f" +
"404142434445464748494a4b4c4d4e4f")
ct = unhexlify("6268c6fa2a80b2d137467f092f657ac0" +
"4d89be2beaa623d61b5a868c8f03ff95" +
"d3dcee23ad2f1ab3a6c80eaf4b140eb0" +
"5de3457f0fbc111a6b43d0763aa422a3" +
"013cf1dc37fe417d1fbfc449b75d4cc5")
digest = unhexlify("3b629ccfbc1119b7319e1dce2cd6fd6d")
cipher = AES.new(key, AES.MODE_GCM, iv).update(aad)
ct2, digest2 = cipher.encrypt_and_digest(pt)
self.assertEqual(ct, ct2)
self.assertEqual(digest, digest2)
class NISTTestVectorsGCM(unittest.TestCase):
def __init__(self, a):
self.use_clmul = True
unittest.TestCase.__init__(self, a)
class NISTTestVectorsGCM_no_clmul(unittest.TestCase):
def __init__(self, a):
self.use_clmul = False
unittest.TestCase.__init__(self, a)
test_vectors_nist = load_test_vectors(
("Cipher", "AES"),
"gcmDecrypt128.rsp",
"GCM decrypt",
{"count": lambda x: int(x)}) or []
test_vectors_nist += load_test_vectors(
("Cipher", "AES"),
"gcmEncryptExtIV128.rsp",
"GCM encrypt",
{"count": lambda x: int(x)}) or []
for idx, tv in enumerate(test_vectors_nist):
# The test vector file contains some directive lines
if isinstance(tv, str):
continue
def single_test(self, tv=tv):
self.description = tv.desc
cipher = AES.new(tv.key, AES.MODE_GCM, nonce=tv.iv,
mac_len=len(tv.tag), use_clmul=self.use_clmul)
cipher.update(tv.aad)
if "FAIL" in tv.others:
self.assertRaises(ValueError, cipher.decrypt_and_verify,
tv.ct, tv.tag)
else:
pt = cipher.decrypt_and_verify(tv.ct, tv.tag)
self.assertEqual(pt, tv.pt)
setattr(NISTTestVectorsGCM, "test_%d" % idx, single_test)
setattr(NISTTestVectorsGCM_no_clmul, "test_%d" % idx, single_test)
class TestVectorsWycheproof(unittest.TestCase):
def __init__(self, wycheproof_warnings, **extra_params):
unittest.TestCase.__init__(self)
self._wycheproof_warnings = wycheproof_warnings
self._extra_params = extra_params
self._id = "None"
def setUp(self):
def filter_tag(group):
return group['tagSize'] // 8
self.tv = load_test_vectors_wycheproof(("Cipher", "wycheproof"),
"aes_gcm_test.json",
"Wycheproof GCM",
group_tag={'tag_size': filter_tag})
def shortDescription(self):
return self._id
def warn(self, tv):
if tv.warning and self._wycheproof_warnings:
import warnings
warnings.warn("Wycheproof warning: %s (%s)" % (self._id, tv.comment))
def test_encrypt(self, tv):
self._id = "Wycheproof Encrypt GCM Test #" + str(tv.id)
try:
cipher = AES.new(tv.key, AES.MODE_GCM, tv.iv, mac_len=tv.tag_size,
**self._extra_params)
except ValueError as e:
if len(tv.iv) == 0 and "Nonce cannot be empty" in str(e):
return
raise e
cipher.update(tv.aad)
ct, tag = cipher.encrypt_and_digest(tv.msg)
if tv.valid:
self.assertEqual(ct, tv.ct)
self.assertEqual(tag, tv.tag)
self.warn(tv)
def test_decrypt(self, tv):
self._id = "Wycheproof Decrypt GCM Test #" + str(tv.id)
try:
cipher = AES.new(tv.key, AES.MODE_GCM, tv.iv, mac_len=tv.tag_size,
**self._extra_params)
except ValueError as e:
if len(tv.iv) == 0 and "Nonce cannot be empty" in str(e):
return
raise e
cipher.update(tv.aad)
try:
pt = cipher.decrypt_and_verify(tv.ct, tv.tag)
except ValueError:
assert not tv.valid
else:
assert tv.valid
self.assertEqual(pt, tv.msg)
self.warn(tv)
def test_corrupt_decrypt(self, tv):
self._id = "Wycheproof Corrupt Decrypt GCM Test #" + str(tv.id)
if len(tv.iv) == 0 or len(tv.ct) < 1:
return
cipher = AES.new(tv.key, AES.MODE_GCM, tv.iv, mac_len=tv.tag_size,
**self._extra_params)
cipher.update(tv.aad)
ct_corrupt = strxor(tv.ct, b"\x00" * (len(tv.ct) - 1) + b"\x01")
self.assertRaises(ValueError, cipher.decrypt_and_verify, ct_corrupt, tv.tag)
def runTest(self):
for tv in self.tv:
self.test_encrypt(tv)
self.test_decrypt(tv)
self.test_corrupt_decrypt(tv)
class TestVariableLength(unittest.TestCase):
def __init__(self, **extra_params):
unittest.TestCase.__init__(self)
self._extra_params = extra_params
def runTest(self):
key = b'0' * 16
h = SHA256.new()
for length in range(160):
nonce = '{0:04d}'.format(length).encode('utf-8')
data = bchr(length) * length
cipher = AES.new(key, AES.MODE_GCM, nonce=nonce, **self._extra_params)
ct, tag = cipher.encrypt_and_digest(data)
h.update(ct)
h.update(tag)
self.assertEqual(h.hexdigest(), "7b7eb1ffbe67a2e53a912067c0ec8e62ebc7ce4d83490ea7426941349811bdf4")
def get_tests(config={}):
from Crypto.Util import _cpu_features
wycheproof_warnings = config.get('wycheproof_warnings')
tests = []
tests += list_test_cases(GcmTests)
tests += list_test_cases(GcmFSMTests)
tests += [TestVectors()]
tests += [TestVectorsWycheproof(wycheproof_warnings)]
tests += list_test_cases(TestVectorsGueronKrasnov)
tests += [TestVariableLength()]
if config.get('slow_tests'):
tests += list_test_cases(NISTTestVectorsGCM)
if _cpu_features.have_clmul():
tests += [TestVectorsWycheproof(wycheproof_warnings, use_clmul=False)]
tests += [TestVariableLength(use_clmul=False)]
if config.get('slow_tests'):
tests += list_test_cases(NISTTestVectorsGCM_no_clmul)
else:
print("Skipping test of PCLMULDQD in AES GCM")
return tests
if __name__ == '__main__':
def suite():
unittest.TestSuite(get_tests())
unittest.main(defaultTest='suite')
PK ! w6 6 Cipher/test_ARC2.pynu [ # -*- coding: utf-8 -*-
#
# SelfTest/Cipher/ARC2.py: Self-test for the Alleged-RC2 cipher
#
# Written in 2008 by Dwayne C. Litzenberger
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the extent that dedication to the public domain is not available,
# everyone is granted a worldwide, perpetual, royalty-free,
# non-exclusive license to exercise all rights associated with the
# contents of this file for any purpose whatsoever.
# No rights are reserved.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# ===================================================================
"""Self-test suite for Crypto.Cipher.ARC2"""
import unittest
from Crypto.Util.py3compat import b, bchr
from Crypto.Cipher import ARC2
# This is a list of (plaintext, ciphertext, key[, description[, extra_params]]) tuples.
test_data = [
# Test vectors from RFC 2268
# 63-bit effective key length
('0000000000000000', 'ebb773f993278eff', '0000000000000000',
'RFC2268-1', dict(effective_keylen=63)),
# 64-bit effective key length
('ffffffffffffffff', '278b27e42e2f0d49', 'ffffffffffffffff',
'RFC2268-2', dict(effective_keylen=64)),
('1000000000000001', '30649edf9be7d2c2', '3000000000000000',
'RFC2268-3', dict(effective_keylen=64)),
#('0000000000000000', '61a8a244adacccf0', '88',
# 'RFC2268-4', dict(effective_keylen=64)),
('0000000000000000', '6ccf4308974c267f', '88bca90e90875a',
'RFC2268-5', dict(effective_keylen=64)),
('0000000000000000', '1a807d272bbe5db1', '88bca90e90875a7f0f79c384627bafb2',
'RFC2268-6', dict(effective_keylen=64)),
# 128-bit effective key length
('0000000000000000', '2269552ab0f85ca6', '88bca90e90875a7f0f79c384627bafb2',
"RFC2268-7", dict(effective_keylen=128)),
('0000000000000000', '5b78d3a43dfff1f1',
'88bca90e90875a7f0f79c384627bafb216f80a6f85920584c42fceb0be255daf1e',
"RFC2268-8", dict(effective_keylen=129)),
# Test vectors from PyCrypto 2.0.1's testdata.py
# 1024-bit effective key length
('0000000000000000', '624fb3e887419e48', '5068696c6970476c617373',
'PCTv201-0'),
('ffffffffffffffff', '79cadef44c4a5a85', '5068696c6970476c617373',
'PCTv201-1'),
('0001020304050607', '90411525b34e4c2c', '5068696c6970476c617373',
'PCTv201-2'),
('0011223344556677', '078656aaba61cbfb', '5068696c6970476c617373',
'PCTv201-3'),
('0000000000000000', 'd7bcc5dbb4d6e56a', 'ffffffffffffffff',
'PCTv201-4'),
('ffffffffffffffff', '7259018ec557b357', 'ffffffffffffffff',
'PCTv201-5'),
('0001020304050607', '93d20a497f2ccb62', 'ffffffffffffffff',
'PCTv201-6'),
('0011223344556677', 'cb15a7f819c0014d', 'ffffffffffffffff',
'PCTv201-7'),
('0000000000000000', '63ac98cdf3843a7a', 'ffffffffffffffff5065746572477265656e6177617953e5ffe553',
'PCTv201-8'),
('ffffffffffffffff', '3fb49e2fa12371dd', 'ffffffffffffffff5065746572477265656e6177617953e5ffe553',
'PCTv201-9'),
('0001020304050607', '46414781ab387d5f', 'ffffffffffffffff5065746572477265656e6177617953e5ffe553',
'PCTv201-10'),
('0011223344556677', 'be09dc81feaca271', 'ffffffffffffffff5065746572477265656e6177617953e5ffe553',
'PCTv201-11'),
('0000000000000000', 'e64221e608be30ab', '53e5ffe553',
'PCTv201-12'),
('ffffffffffffffff', '862bc60fdcd4d9a9', '53e5ffe553',
'PCTv201-13'),
('0001020304050607', '6a34da50fa5e47de', '53e5ffe553',
'PCTv201-14'),
('0011223344556677', '584644c34503122c', '53e5ffe553',
'PCTv201-15'),
]
class BufferOverflowTest(unittest.TestCase):
# Test a buffer overflow found in older versions of PyCrypto
def runTest(self):
"""ARC2 with keylength > 128"""
key = b("x") * 16384
self.assertRaises(ValueError, ARC2.new, key, ARC2.MODE_ECB)
class KeyLength(unittest.TestCase):
def runTest(self):
ARC2.new(b'\x00' * 16, ARC2.MODE_ECB, effective_keylen=40)
self.assertRaises(ValueError, ARC2.new, bchr(0) * 4, ARC2.MODE_ECB)
self.assertRaises(ValueError, ARC2.new, bchr(0) * 129, ARC2.MODE_ECB)
self.assertRaises(ValueError, ARC2.new, bchr(0) * 16, ARC2.MODE_ECB,
effective_keylen=39)
self.assertRaises(ValueError, ARC2.new, bchr(0) * 16, ARC2.MODE_ECB,
effective_keylen=1025)
class TestOutput(unittest.TestCase):
def runTest(self):
# Encrypt/Decrypt data and test output parameter
cipher = ARC2.new(b'4'*16, ARC2.MODE_ECB)
pt = b'5' * 16
ct = cipher.encrypt(pt)
output = bytearray(16)
res = cipher.encrypt(pt, output=output)
self.assertEqual(ct, output)
self.assertEqual(res, None)
res = cipher.decrypt(ct, output=output)
self.assertEqual(pt, output)
self.assertEqual(res, None)
output = memoryview(bytearray(16))
cipher.encrypt(pt, output=output)
self.assertEqual(ct, output)
cipher.decrypt(ct, output=output)
self.assertEqual(pt, output)
self.assertRaises(TypeError, cipher.encrypt, pt, output=b'0'*16)
self.assertRaises(TypeError, cipher.decrypt, ct, output=b'0'*16)
shorter_output = bytearray(7)
self.assertRaises(ValueError, cipher.encrypt, pt, output=shorter_output)
self.assertRaises(ValueError, cipher.decrypt, ct, output=shorter_output)
def get_tests(config={}):
from Crypto.Cipher import ARC2
from .common import make_block_tests
tests = make_block_tests(ARC2, "ARC2", test_data)
tests.append(BufferOverflowTest())
tests.append(KeyLength())
tests += [TestOutput()]
return tests
if __name__ == '__main__':
import unittest
suite = lambda: unittest.TestSuite(get_tests())
unittest.main(defaultTest='suite')
# vim:set ts=4 sw=4 sts=4 expandtab:
PK ! ݡ Cipher/test_DES3.pynu [ # -*- coding: utf-8 -*-
#
# SelfTest/Cipher/DES3.py: Self-test for the Triple-DES cipher
#
# Written in 2008 by Dwayne C. Litzenberger
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the extent that dedication to the public domain is not available,
# everyone is granted a worldwide, perpetual, royalty-free,
# non-exclusive license to exercise all rights associated with the
# contents of this file for any purpose whatsoever.
# No rights are reserved.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# ===================================================================
"""Self-test suite for Crypto.Cipher.DES3"""
import unittest
from binascii import hexlify, unhexlify
from Crypto.Cipher import DES3
from Crypto.Util.strxor import strxor_c
from Crypto.Util.py3compat import bchr, tostr
from Crypto.SelfTest.loader import load_test_vectors
from Crypto.SelfTest.st_common import list_test_cases
# This is a list of (plaintext, ciphertext, key, description) tuples.
test_data = [
# Test vector from Appendix B of NIST SP 800-67
# "Recommendation for the Triple Data Encryption Algorithm (TDEA) Block
# Cipher"
# http://csrc.nist.gov/publications/nistpubs/800-67/SP800-67.pdf
('54686520717566636b2062726f776e20666f78206a756d70',
'a826fd8ce53b855fcce21c8112256fe668d5c05dd9b6b900',
'0123456789abcdef23456789abcdef01456789abcdef0123',
'NIST SP800-67 B.1'),
# This test is designed to test the DES3 API, not the correctness of the
# output.
('21e81b7ade88a259', '5c577d4d9b20c0f8',
'9b397ebf81b1181e282f4bb8adbadc6b', 'Two-key 3DES'),
]
# NIST CAVP test vectors
nist_tdes_mmt_files = ("TECBMMT2.rsp", "TECBMMT3.rsp")
for tdes_file in nist_tdes_mmt_files:
test_vectors = load_test_vectors(
("Cipher", "TDES"),
tdes_file,
"TDES ECB (%s)" % tdes_file,
{"count": lambda x: int(x)}) or []
for index, tv in enumerate(test_vectors):
# The test vector file contains some directive lines
if isinstance(tv, str):
continue
key = tv.key1 + tv.key2 + tv.key3
test_data_item = (tostr(hexlify(tv.plaintext)),
tostr(hexlify(tv.ciphertext)),
tostr(hexlify(key)),
"%s (%s)" % (tdes_file, index))
test_data.append(test_data_item)
class CheckParity(unittest.TestCase):
def test_parity_option2(self):
before_2k = unhexlify("CABF326FA56734324FFCCABCDEFACABF")
after_2k = DES3.adjust_key_parity(before_2k)
self.assertEqual(after_2k,
unhexlify("CBBF326EA46734324FFDCBBCDFFBCBBF"))
def test_parity_option3(self):
before_3k = unhexlify("AAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBCCCCCCCCCCCCCCCC")
after_3k = DES3.adjust_key_parity(before_3k)
self.assertEqual(after_3k,
unhexlify("ABABABABABABABABBABABABABABABABACDCDCDCDCDCDCDCD"))
def test_degradation(self):
sub_key1 = bchr(1) * 8
sub_key2 = bchr(255) * 8
# K1 == K2
self.assertRaises(ValueError, DES3.adjust_key_parity,
sub_key1 * 2 + sub_key2)
# K2 == K3
self.assertRaises(ValueError, DES3.adjust_key_parity,
sub_key1 + sub_key2 * 2)
# K1 == K2 == K3
self.assertRaises(ValueError, DES3.adjust_key_parity,
sub_key1 * 3)
# K1 == K2 (with different parity)
self.assertRaises(ValueError, DES3.adjust_key_parity,
sub_key1 + strxor_c(sub_key1, 1) + sub_key2)
class DegenerateToDESTest(unittest.TestCase):
def runTest(self):
sub_key1 = bchr(1) * 8
sub_key2 = bchr(255) * 8
# K1 == K2
self.assertRaises(ValueError, DES3.new,
sub_key1 * 2 + sub_key2,
DES3.MODE_ECB)
# K2 == K3
self.assertRaises(ValueError, DES3.new,
sub_key1 + sub_key2 * 2,
DES3.MODE_ECB)
# K1 == K2 == K3
self.assertRaises(ValueError, DES3.new,
sub_key1 * 3,
DES3.MODE_ECB)
# K2 == K3 (parity is ignored)
self.assertRaises(ValueError, DES3.new,
sub_key1 + sub_key2 + strxor_c(sub_key2, 0x1),
DES3.MODE_ECB)
class TestOutput(unittest.TestCase):
def runTest(self):
# Encrypt/Decrypt data and test output parameter
cipher = DES3.new(b'4'*8 + b'G'*8 + b'T'*8, DES3.MODE_ECB)
pt = b'5' * 16
ct = cipher.encrypt(pt)
output = bytearray(16)
res = cipher.encrypt(pt, output=output)
self.assertEqual(ct, output)
self.assertEqual(res, None)
res = cipher.decrypt(ct, output=output)
self.assertEqual(pt, output)
self.assertEqual(res, None)
output = memoryview(bytearray(16))
cipher.encrypt(pt, output=output)
self.assertEqual(ct, output)
cipher.decrypt(ct, output=output)
self.assertEqual(pt, output)
self.assertRaises(TypeError, cipher.encrypt, pt, output=b'0'*16)
self.assertRaises(TypeError, cipher.decrypt, ct, output=b'0'*16)
shorter_output = bytearray(7)
self.assertRaises(ValueError, cipher.encrypt, pt, output=shorter_output)
self.assertRaises(ValueError, cipher.decrypt, ct, output=shorter_output)
def get_tests(config={}):
from .common import make_block_tests
tests = []
tests = make_block_tests(DES3, "DES3", test_data)
tests.append(DegenerateToDESTest())
tests += list_test_cases(CheckParity)
tests += [TestOutput()]
return tests
if __name__ == '__main__':
import unittest
def suite():
unittest.TestSuite(get_tests())
unittest.main(defaultTest='suite')
# vim:set ts=4 sw=4 sts=4 expandtab:
PK ! Gp Cipher/test_OCB.pynu [ # ===================================================================
#
# Copyright (c) 2014, Legrandin
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ===================================================================
import unittest
from binascii import unhexlify
from Crypto.Util.py3compat import b, tobytes, bchr
from Crypto.Util.number import long_to_bytes
from Crypto.SelfTest.loader import load_test_vectors
from Crypto.SelfTest.st_common import list_test_cases
from Crypto.Cipher import AES
from Crypto.Hash import SHAKE128
def get_tag_random(tag, length):
return SHAKE128.new(data=tobytes(tag)).read(length)
class OcbTests(unittest.TestCase):
key_128 = get_tag_random("key_128", 16)
nonce_96 = get_tag_random("nonce_128", 12)
data = get_tag_random("data", 128)
def test_loopback_128(self):
cipher = AES.new(self.key_128, AES.MODE_OCB, nonce=self.nonce_96)
pt = get_tag_random("plaintext", 16 * 100)
ct, mac = cipher.encrypt_and_digest(pt)
cipher = AES.new(self.key_128, AES.MODE_OCB, nonce=self.nonce_96)
pt2 = cipher.decrypt_and_verify(ct, mac)
self.assertEqual(pt, pt2)
def test_nonce(self):
# Nonce is optional
AES.new(self.key_128, AES.MODE_OCB)
cipher = AES.new(self.key_128, AES.MODE_OCB, self.nonce_96)
ct = cipher.encrypt(self.data)
cipher = AES.new(self.key_128, AES.MODE_OCB, nonce=self.nonce_96)
self.assertEqual(ct, cipher.encrypt(self.data))
def test_nonce_must_be_bytes(self):
self.assertRaises(TypeError, AES.new, self.key_128, AES.MODE_OCB,
nonce=u'test12345678')
def test_nonce_length(self):
# nonce cannot be empty
self.assertRaises(ValueError, AES.new, self.key_128, AES.MODE_OCB,
nonce=b(""))
# nonce can be up to 15 bytes long
for length in range(1, 16):
AES.new(self.key_128, AES.MODE_OCB, nonce=self.data[:length])
self.assertRaises(ValueError, AES.new, self.key_128, AES.MODE_OCB,
nonce=self.data)
def test_block_size_128(self):
cipher = AES.new(self.key_128, AES.MODE_OCB, nonce=self.nonce_96)
self.assertEqual(cipher.block_size, AES.block_size)
# By default, a 15 bytes long nonce is randomly generated
nonce1 = AES.new(self.key_128, AES.MODE_OCB).nonce
nonce2 = AES.new(self.key_128, AES.MODE_OCB).nonce
self.assertEqual(len(nonce1), 15)
self.assertNotEqual(nonce1, nonce2)
def test_nonce_attribute(self):
cipher = AES.new(self.key_128, AES.MODE_OCB, nonce=self.nonce_96)
self.assertEqual(cipher.nonce, self.nonce_96)
# By default, a 15 bytes long nonce is randomly generated
nonce1 = AES.new(self.key_128, AES.MODE_OCB).nonce
nonce2 = AES.new(self.key_128, AES.MODE_OCB).nonce
self.assertEqual(len(nonce1), 15)
self.assertNotEqual(nonce1, nonce2)
def test_unknown_parameters(self):
self.assertRaises(TypeError, AES.new, self.key_128, AES.MODE_OCB,
self.nonce_96, 7)
self.assertRaises(TypeError, AES.new, self.key_128, AES.MODE_OCB,
nonce=self.nonce_96, unknown=7)
# But some are only known by the base cipher
# (e.g. use_aesni consumed by the AES module)
AES.new(self.key_128, AES.MODE_OCB, nonce=self.nonce_96,
use_aesni=False)
def test_null_encryption_decryption(self):
for func in "encrypt", "decrypt":
cipher = AES.new(self.key_128, AES.MODE_OCB, nonce=self.nonce_96)
result = getattr(cipher, func)(b(""))
self.assertEqual(result, b(""))
def test_either_encrypt_or_decrypt(self):
cipher = AES.new(self.key_128, AES.MODE_OCB, nonce=self.nonce_96)
cipher.encrypt(b("xyz"))
self.assertRaises(TypeError, cipher.decrypt, b("xyz"))
cipher = AES.new(self.key_128, AES.MODE_OCB, nonce=self.nonce_96)
cipher.decrypt(b("xyz"))
self.assertRaises(TypeError, cipher.encrypt, b("xyz"))
def test_data_must_be_bytes(self):
cipher = AES.new(self.key_128, AES.MODE_OCB, nonce=self.nonce_96)
self.assertRaises(TypeError, cipher.encrypt, u'test1234567890-*')
cipher = AES.new(self.key_128, AES.MODE_OCB, nonce=self.nonce_96)
self.assertRaises(TypeError, cipher.decrypt, u'test1234567890-*')
def test_mac_len(self):
# Invalid MAC length
self.assertRaises(ValueError, AES.new, self.key_128, AES.MODE_OCB,
nonce=self.nonce_96, mac_len=7)
self.assertRaises(ValueError, AES.new, self.key_128, AES.MODE_OCB,
nonce=self.nonce_96, mac_len=16+1)
# Valid MAC length
for mac_len in range(8, 16 + 1):
cipher = AES.new(self.key_128, AES.MODE_OCB, nonce=self.nonce_96,
mac_len=mac_len)
_, mac = cipher.encrypt_and_digest(self.data)
self.assertEqual(len(mac), mac_len)
# Default MAC length
cipher = AES.new(self.key_128, AES.MODE_OCB, nonce=self.nonce_96)
_, mac = cipher.encrypt_and_digest(self.data)
self.assertEqual(len(mac), 16)
def test_invalid_mac(self):
from Crypto.Util.strxor import strxor_c
cipher = AES.new(self.key_128, AES.MODE_OCB, nonce=self.nonce_96)
ct, mac = cipher.encrypt_and_digest(self.data)
invalid_mac = strxor_c(mac, 0x01)
cipher = AES.new(self.key_128, AES.MODE_OCB, nonce=self.nonce_96)
self.assertRaises(ValueError, cipher.decrypt_and_verify, ct,
invalid_mac)
def test_hex_mac(self):
cipher = AES.new(self.key_128, AES.MODE_OCB, nonce=self.nonce_96)
mac_hex = cipher.hexdigest()
self.assertEqual(cipher.digest(), unhexlify(mac_hex))
cipher = AES.new(self.key_128, AES.MODE_OCB, nonce=self.nonce_96)
cipher.hexverify(mac_hex)
def test_message_chunks(self):
# Validate that both associated data and plaintext/ciphertext
# can be broken up in chunks of arbitrary length
auth_data = get_tag_random("authenticated data", 127)
plaintext = get_tag_random("plaintext", 127)
cipher = AES.new(self.key_128, AES.MODE_OCB, nonce=self.nonce_96)
cipher.update(auth_data)
ciphertext, ref_mac = cipher.encrypt_and_digest(plaintext)
def break_up(data, chunk_length):
return [data[i:i+chunk_length] for i in range(0, len(data),
chunk_length)]
# Encryption
for chunk_length in 1, 2, 3, 7, 10, 13, 16, 40, 80, 128:
cipher = AES.new(self.key_128, AES.MODE_OCB, nonce=self.nonce_96)
for chunk in break_up(auth_data, chunk_length):
cipher.update(chunk)
pt2 = b("")
for chunk in break_up(ciphertext, chunk_length):
pt2 += cipher.decrypt(chunk)
pt2 += cipher.decrypt()
self.assertEqual(plaintext, pt2)
cipher.verify(ref_mac)
# Decryption
for chunk_length in 1, 2, 3, 7, 10, 13, 16, 40, 80, 128:
cipher = AES.new(self.key_128, AES.MODE_OCB, nonce=self.nonce_96)
for chunk in break_up(auth_data, chunk_length):
cipher.update(chunk)
ct2 = b("")
for chunk in break_up(plaintext, chunk_length):
ct2 += cipher.encrypt(chunk)
ct2 += cipher.encrypt()
self.assertEqual(ciphertext, ct2)
self.assertEqual(cipher.digest(), ref_mac)
def test_bytearray(self):
# Encrypt
key_ba = bytearray(self.key_128)
nonce_ba = bytearray(self.nonce_96)
header_ba = bytearray(self.data)
data_ba = bytearray(self.data)
cipher1 = AES.new(self.key_128,
AES.MODE_OCB,
nonce=self.nonce_96)
cipher1.update(self.data)
ct = cipher1.encrypt(self.data) + cipher1.encrypt()
tag = cipher1.digest()
cipher2 = AES.new(key_ba,
AES.MODE_OCB,
nonce=nonce_ba)
key_ba[:3] = b"\xFF\xFF\xFF"
nonce_ba[:3] = b"\xFF\xFF\xFF"
cipher2.update(header_ba)
header_ba[:3] = b"\xFF\xFF\xFF"
ct_test = cipher2.encrypt(data_ba) + cipher2.encrypt()
data_ba[:3] = b"\xFF\xFF\xFF"
tag_test = cipher2.digest()
self.assertEqual(ct, ct_test)
self.assertEqual(tag, tag_test)
self.assertEqual(cipher1.nonce, cipher2.nonce)
# Decrypt
key_ba = bytearray(self.key_128)
nonce_ba = bytearray(self.nonce_96)
header_ba = bytearray(self.data)
del data_ba
cipher4 = AES.new(key_ba,
AES.MODE_OCB,
nonce=nonce_ba)
key_ba[:3] = b"\xFF\xFF\xFF"
nonce_ba[:3] = b"\xFF\xFF\xFF"
cipher4.update(header_ba)
header_ba[:3] = b"\xFF\xFF\xFF"
pt_test = cipher4.decrypt_and_verify(bytearray(ct_test), bytearray(tag_test))
self.assertEqual(self.data, pt_test)
def test_memoryview(self):
# Encrypt
key_mv = memoryview(bytearray(self.key_128))
nonce_mv = memoryview(bytearray(self.nonce_96))
header_mv = memoryview(bytearray(self.data))
data_mv = memoryview(bytearray(self.data))
cipher1 = AES.new(self.key_128,
AES.MODE_OCB,
nonce=self.nonce_96)
cipher1.update(self.data)
ct = cipher1.encrypt(self.data) + cipher1.encrypt()
tag = cipher1.digest()
cipher2 = AES.new(key_mv,
AES.MODE_OCB,
nonce=nonce_mv)
key_mv[:3] = b"\xFF\xFF\xFF"
nonce_mv[:3] = b"\xFF\xFF\xFF"
cipher2.update(header_mv)
header_mv[:3] = b"\xFF\xFF\xFF"
ct_test = cipher2.encrypt(data_mv) + cipher2.encrypt()
data_mv[:3] = b"\xFF\xFF\xFF"
tag_test = cipher2.digest()
self.assertEqual(ct, ct_test)
self.assertEqual(tag, tag_test)
self.assertEqual(cipher1.nonce, cipher2.nonce)
# Decrypt
key_mv = memoryview(bytearray(self.key_128))
nonce_mv = memoryview(bytearray(self.nonce_96))
header_mv = memoryview(bytearray(self.data))
del data_mv
cipher4 = AES.new(key_mv,
AES.MODE_OCB,
nonce=nonce_mv)
key_mv[:3] = b"\xFF\xFF\xFF"
nonce_mv[:3] = b"\xFF\xFF\xFF"
cipher4.update(header_mv)
header_mv[:3] = b"\xFF\xFF\xFF"
pt_test = cipher4.decrypt_and_verify(memoryview(ct_test), memoryview(tag_test))
self.assertEqual(self.data, pt_test)
class OcbFSMTests(unittest.TestCase):
key_128 = get_tag_random("key_128", 16)
nonce_96 = get_tag_random("nonce_128", 12)
data = get_tag_random("data", 128)
def test_valid_init_encrypt_decrypt_digest_verify(self):
# No authenticated data, fixed plaintext
# Verify path INIT->ENCRYPT->ENCRYPT(NONE)->DIGEST
cipher = AES.new(self.key_128, AES.MODE_OCB,
nonce=self.nonce_96)
ct = cipher.encrypt(self.data)
ct += cipher.encrypt()
mac = cipher.digest()
# Verify path INIT->DECRYPT->DECRYPT(NONCE)->VERIFY
cipher = AES.new(self.key_128, AES.MODE_OCB,
nonce=self.nonce_96)
cipher.decrypt(ct)
cipher.decrypt()
cipher.verify(mac)
def test_invalid_init_encrypt_decrypt_digest_verify(self):
# No authenticated data, fixed plaintext
# Verify path INIT->ENCRYPT->DIGEST
cipher = AES.new(self.key_128, AES.MODE_OCB,
nonce=self.nonce_96)
ct = cipher.encrypt(self.data)
self.assertRaises(TypeError, cipher.digest)
# Verify path INIT->DECRYPT->VERIFY
cipher = AES.new(self.key_128, AES.MODE_OCB,
nonce=self.nonce_96)
cipher.decrypt(ct)
self.assertRaises(TypeError, cipher.verify)
def test_valid_init_update_digest_verify(self):
# No plaintext, fixed authenticated data
# Verify path INIT->UPDATE->DIGEST
cipher = AES.new(self.key_128, AES.MODE_OCB,
nonce=self.nonce_96)
cipher.update(self.data)
mac = cipher.digest()
# Verify path INIT->UPDATE->VERIFY
cipher = AES.new(self.key_128, AES.MODE_OCB,
nonce=self.nonce_96)
cipher.update(self.data)
cipher.verify(mac)
def test_valid_full_path(self):
# Fixed authenticated data, fixed plaintext
# Verify path INIT->UPDATE->ENCRYPT->ENCRYPT(NONE)->DIGEST
cipher = AES.new(self.key_128, AES.MODE_OCB,
nonce=self.nonce_96)
cipher.update(self.data)
ct = cipher.encrypt(self.data)
ct += cipher.encrypt()
mac = cipher.digest()
# Verify path INIT->UPDATE->DECRYPT->DECRYPT(NONE)->VERIFY
cipher = AES.new(self.key_128, AES.MODE_OCB,
nonce=self.nonce_96)
cipher.update(self.data)
cipher.decrypt(ct)
cipher.decrypt()
cipher.verify(mac)
# Verify path INIT->UPDATE->ENCRYPT->ENCRYPT_AND_DIGEST
cipher = AES.new(self.key_128, AES.MODE_OCB,
nonce=self.nonce_96)
cipher.update(self.data)
ct1 = cipher.encrypt(self.data[:2])
ct2, mac = cipher.encrypt_and_digest(self.data[2:])
# Verify path INIT->UPDATE->DECRYPT->DECRYPT_AND_VERIFY
cipher = AES.new(self.key_128, AES.MODE_OCB,
nonce=self.nonce_96)
cipher.update(self.data)
cipher.decrypt(ct1)
cipher.decrypt_and_verify(ct2, mac)
def test_invalid_encrypt_after_final(self):
cipher = AES.new(self.key_128, AES.MODE_OCB,
nonce=self.nonce_96)
cipher.update(self.data)
cipher.encrypt(self.data)
cipher.encrypt()
self.assertRaises(TypeError, cipher.encrypt, self.data)
def test_invalid_decrypt_after_final(self):
cipher = AES.new(self.key_128, AES.MODE_OCB,
nonce=self.nonce_96)
cipher.update(self.data)
cipher.decrypt(self.data)
cipher.decrypt()
self.assertRaises(TypeError, cipher.decrypt, self.data)
def test_valid_init_digest(self):
# Verify path INIT->DIGEST
cipher = AES.new(self.key_128, AES.MODE_OCB, nonce=self.nonce_96)
cipher.digest()
def test_valid_init_verify(self):
# Verify path INIT->VERIFY
cipher = AES.new(self.key_128, AES.MODE_OCB, nonce=self.nonce_96)
mac = cipher.digest()
cipher = AES.new(self.key_128, AES.MODE_OCB, nonce=self.nonce_96)
cipher.verify(mac)
def test_valid_multiple_encrypt_or_decrypt(self):
for method_name in "encrypt", "decrypt":
for auth_data in (None, b("333"), self.data,
self.data + b("3")):
cipher = AES.new(self.key_128, AES.MODE_OCB,
nonce=self.nonce_96)
if auth_data is not None:
cipher.update(auth_data)
method = getattr(cipher, method_name)
method(self.data)
method(self.data)
method(self.data)
method(self.data)
method()
def test_valid_multiple_digest_or_verify(self):
# Multiple calls to digest
cipher = AES.new(self.key_128, AES.MODE_OCB, nonce=self.nonce_96)
cipher.update(self.data)
first_mac = cipher.digest()
for x in range(4):
self.assertEqual(first_mac, cipher.digest())
# Multiple calls to verify
cipher = AES.new(self.key_128, AES.MODE_OCB, nonce=self.nonce_96)
cipher.update(self.data)
for x in range(5):
cipher.verify(first_mac)
def test_valid_encrypt_and_digest_decrypt_and_verify(self):
# encrypt_and_digest
cipher = AES.new(self.key_128, AES.MODE_OCB, nonce=self.nonce_96)
cipher.update(self.data)
ct, mac = cipher.encrypt_and_digest(self.data)
# decrypt_and_verify
cipher = AES.new(self.key_128, AES.MODE_OCB, nonce=self.nonce_96)
cipher.update(self.data)
pt = cipher.decrypt_and_verify(ct, mac)
self.assertEqual(self.data, pt)
def test_invalid_mixing_encrypt_decrypt(self):
# Once per method, with or without assoc. data
for method1_name, method2_name in (("encrypt", "decrypt"),
("decrypt", "encrypt")):
for assoc_data_present in (True, False):
cipher = AES.new(self.key_128, AES.MODE_OCB,
nonce=self.nonce_96)
if assoc_data_present:
cipher.update(self.data)
getattr(cipher, method1_name)(self.data)
self.assertRaises(TypeError, getattr(cipher, method2_name),
self.data)
def test_invalid_encrypt_or_update_after_digest(self):
for method_name in "encrypt", "update":
cipher = AES.new(self.key_128, AES.MODE_OCB, nonce=self.nonce_96)
cipher.encrypt(self.data)
cipher.encrypt()
cipher.digest()
self.assertRaises(TypeError, getattr(cipher, method_name),
self.data)
cipher = AES.new(self.key_128, AES.MODE_OCB, nonce=self.nonce_96)
cipher.encrypt_and_digest(self.data)
def test_invalid_decrypt_or_update_after_verify(self):
cipher = AES.new(self.key_128, AES.MODE_OCB, nonce=self.nonce_96)
ct = cipher.encrypt(self.data)
ct += cipher.encrypt()
mac = cipher.digest()
for method_name in "decrypt", "update":
cipher = AES.new(self.key_128, AES.MODE_OCB, nonce=self.nonce_96)
cipher.decrypt(ct)
cipher.decrypt()
cipher.verify(mac)
self.assertRaises(TypeError, getattr(cipher, method_name),
self.data)
cipher = AES.new(self.key_128, AES.MODE_OCB, nonce=self.nonce_96)
cipher.decrypt_and_verify(ct, mac)
self.assertRaises(TypeError, getattr(cipher, method_name),
self.data)
def algo_rfc7253(keylen, taglen, noncelen):
"""Implement the algorithm at page 18 of RFC 7253"""
key = bchr(0) * (keylen // 8 - 1) + bchr(taglen)
C = b""
for i in range(128):
S = bchr(0) * i
N = long_to_bytes(3 * i + 1, noncelen // 8)
cipher = AES.new(key, AES.MODE_OCB, nonce=N, mac_len=taglen // 8)
cipher.update(S)
C += cipher.encrypt(S) + cipher.encrypt() + cipher.digest()
N = long_to_bytes(3 * i + 2, noncelen // 8)
cipher = AES.new(key, AES.MODE_OCB, nonce=N, mac_len=taglen // 8)
C += cipher.encrypt(S) + cipher.encrypt() + cipher.digest()
N = long_to_bytes(3 * i + 3, noncelen // 8)
cipher = AES.new(key, AES.MODE_OCB, nonce=N, mac_len=taglen // 8)
cipher.update(S)
C += cipher.encrypt() + cipher.digest()
N = long_to_bytes(385, noncelen // 8)
cipher = AES.new(key, AES.MODE_OCB, nonce=N, mac_len=taglen // 8)
cipher.update(C)
return cipher.encrypt() + cipher.digest()
class OcbRfc7253Test(unittest.TestCase):
# Tuple with
# - nonce
# - authenticated data
# - plaintext
# - ciphertext and 16 byte MAC tag
tv1_key = "000102030405060708090A0B0C0D0E0F"
tv1 = (
(
"BBAA99887766554433221100",
"",
"",
"785407BFFFC8AD9EDCC5520AC9111EE6"
),
(
"BBAA99887766554433221101",
"0001020304050607",
"0001020304050607",
"6820B3657B6F615A5725BDA0D3B4EB3A257C9AF1F8F03009"
),
(
"BBAA99887766554433221102",
"0001020304050607",
"",
"81017F8203F081277152FADE694A0A00"
),
(
"BBAA99887766554433221103",
"",
"0001020304050607",
"45DD69F8F5AAE72414054CD1F35D82760B2CD00D2F99BFA9"
),
(
"BBAA99887766554433221104",
"000102030405060708090A0B0C0D0E0F",
"000102030405060708090A0B0C0D0E0F",
"571D535B60B277188BE5147170A9A22C3AD7A4FF3835B8C5"
"701C1CCEC8FC3358"
),
(
"BBAA99887766554433221105",
"000102030405060708090A0B0C0D0E0F",
"",
"8CF761B6902EF764462AD86498CA6B97"
),
(
"BBAA99887766554433221106",
"",
"000102030405060708090A0B0C0D0E0F",
"5CE88EC2E0692706A915C00AEB8B2396F40E1C743F52436B"
"DF06D8FA1ECA343D"
),
(
"BBAA99887766554433221107",
"000102030405060708090A0B0C0D0E0F1011121314151617",
"000102030405060708090A0B0C0D0E0F1011121314151617",
"1CA2207308C87C010756104D8840CE1952F09673A448A122"
"C92C62241051F57356D7F3C90BB0E07F"
),
(
"BBAA99887766554433221108",
"000102030405060708090A0B0C0D0E0F1011121314151617",
"",
"6DC225A071FC1B9F7C69F93B0F1E10DE"
),
(
"BBAA99887766554433221109",
"",
"000102030405060708090A0B0C0D0E0F1011121314151617",
"221BD0DE7FA6FE993ECCD769460A0AF2D6CDED0C395B1C3C"
"E725F32494B9F914D85C0B1EB38357FF"
),
(
"BBAA9988776655443322110A",
"000102030405060708090A0B0C0D0E0F1011121314151617"
"18191A1B1C1D1E1F",
"000102030405060708090A0B0C0D0E0F1011121314151617"
"18191A1B1C1D1E1F",
"BD6F6C496201C69296C11EFD138A467ABD3C707924B964DE"
"AFFC40319AF5A48540FBBA186C5553C68AD9F592A79A4240"
),
(
"BBAA9988776655443322110B",
"000102030405060708090A0B0C0D0E0F1011121314151617"
"18191A1B1C1D1E1F",
"",
"FE80690BEE8A485D11F32965BC9D2A32"
),
(
"BBAA9988776655443322110C",
"",
"000102030405060708090A0B0C0D0E0F1011121314151617"
"18191A1B1C1D1E1F",
"2942BFC773BDA23CABC6ACFD9BFD5835BD300F0973792EF4"
"6040C53F1432BCDFB5E1DDE3BC18A5F840B52E653444D5DF"
),
(
"BBAA9988776655443322110D",
"000102030405060708090A0B0C0D0E0F1011121314151617"
"18191A1B1C1D1E1F2021222324252627",
"000102030405060708090A0B0C0D0E0F1011121314151617"
"18191A1B1C1D1E1F2021222324252627",
"D5CA91748410C1751FF8A2F618255B68A0A12E093FF45460"
"6E59F9C1D0DDC54B65E8628E568BAD7AED07BA06A4A69483"
"A7035490C5769E60"
),
(
"BBAA9988776655443322110E",
"000102030405060708090A0B0C0D0E0F1011121314151617"
"18191A1B1C1D1E1F2021222324252627",
"",
"C5CD9D1850C141E358649994EE701B68"
),
(
"BBAA9988776655443322110F",
"",
"000102030405060708090A0B0C0D0E0F1011121314151617"
"18191A1B1C1D1E1F2021222324252627",
"4412923493C57D5DE0D700F753CCE0D1D2D95060122E9F15"
"A5DDBFC5787E50B5CC55EE507BCB084E479AD363AC366B95"
"A98CA5F3000B1479"
)
)
# Tuple with
# - key
# - nonce
# - authenticated data
# - plaintext
# - ciphertext and 12 byte MAC tag
tv2 = (
"0F0E0D0C0B0A09080706050403020100",
"BBAA9988776655443322110D",
"000102030405060708090A0B0C0D0E0F1011121314151617"
"18191A1B1C1D1E1F2021222324252627",
"000102030405060708090A0B0C0D0E0F1011121314151617"
"18191A1B1C1D1E1F2021222324252627",
"1792A4E31E0755FB03E31B22116E6C2DDF9EFD6E33D536F1"
"A0124B0A55BAE884ED93481529C76B6AD0C515F4D1CDD4FD"
"AC4F02AA"
)
# Tuple with
# - key length
# - MAC tag length
# - Expected output
tv3 = (
(128, 128, "67E944D23256C5E0B6C61FA22FDF1EA2"),
(192, 128, "F673F2C3E7174AAE7BAE986CA9F29E17"),
(256, 128, "D90EB8E9C977C88B79DD793D7FFA161C"),
(128, 96, "77A3D8E73589158D25D01209"),
(192, 96, "05D56EAD2752C86BE6932C5E"),
(256, 96, "5458359AC23B0CBA9E6330DD"),
(128, 64, "192C9B7BD90BA06A"),
(192, 64, "0066BC6E0EF34E24"),
(256, 64, "7D4EA5D445501CBE"),
)
def test1(self):
key = unhexlify(b(self.tv1_key))
for tv in self.tv1:
nonce, aad, pt, ct = [unhexlify(b(x)) for x in tv]
ct, mac_tag = ct[:-16], ct[-16:]
cipher = AES.new(key, AES.MODE_OCB, nonce=nonce)
cipher.update(aad)
ct2 = cipher.encrypt(pt) + cipher.encrypt()
self.assertEqual(ct, ct2)
self.assertEqual(mac_tag, cipher.digest())
cipher = AES.new(key, AES.MODE_OCB, nonce=nonce)
cipher.update(aad)
pt2 = cipher.decrypt(ct) + cipher.decrypt()
self.assertEqual(pt, pt2)
cipher.verify(mac_tag)
def test2(self):
key, nonce, aad, pt, ct = [unhexlify(b(x)) for x in self.tv2]
ct, mac_tag = ct[:-12], ct[-12:]
cipher = AES.new(key, AES.MODE_OCB, nonce=nonce, mac_len=12)
cipher.update(aad)
ct2 = cipher.encrypt(pt) + cipher.encrypt()
self.assertEqual(ct, ct2)
self.assertEqual(mac_tag, cipher.digest())
cipher = AES.new(key, AES.MODE_OCB, nonce=nonce, mac_len=12)
cipher.update(aad)
pt2 = cipher.decrypt(ct) + cipher.decrypt()
self.assertEqual(pt, pt2)
cipher.verify(mac_tag)
def test3(self):
for keylen, taglen, result in self.tv3:
result2 = algo_rfc7253(keylen, taglen, 96)
self.assertEqual(unhexlify(b(result)), result2)
class OcbDkgTest(unittest.TestCase):
"""Test vectors from https://gitlab.com/dkg/ocb-test-vectors"""
def test_1_2(self):
tvs = []
for fi in (1, 2):
for nb in (104, 112, 120):
tv_file = load_test_vectors(("Cipher", "AES"),
"test-vector-%d-nonce%d.txt" % (fi, nb),
"DKG tests, %d, %d bits" % (fi, nb),
{})
if tv_file is None:
break
key = tv_file[0].k
for tv in tv_file[1:]:
tv.k = key
tvs.append(tv)
for tv in tvs:
k, n, a, p, c = tv.k, tv.n, tv.a, tv.p, tv.c
mac_len = len(c) - len(p)
cipher = AES.new(k, AES.MODE_OCB, nonce=n, mac_len=mac_len)
cipher.update(a)
c_out, tag_out = cipher.encrypt_and_digest(p)
self.assertEqual(c, c_out + tag_out)
def test_3(self):
def check(keylen, taglen, noncelen, exp):
result = algo_rfc7253(keylen, taglen, noncelen)
self.assertEqual(result, unhexlify(exp))
# test-vector-3-nonce104.txt
check(128, 128, 104, "C47F5F0341E15326D4D1C46F47F05062")
check(192, 128, 104, "95B9167A38EB80495DFC561A8486E109")
check(256, 128, 104, "AFE1CDDB97028FD92F8FB3C8CFBA7D83")
check(128, 96, 104, "F471B4983BA80946DF217A54")
check(192, 96, 104, "5AE828BC51C24D85FA5CC7B2")
check(256, 96, 104, "8C8335982E2B734616CAD14C")
check(128, 64, 104, "B553F74B85FD1E5B")
check(192, 64, 104, "3B49D20E513531F9")
check(256, 64, 104, "ED6DA5B1216BF8BB")
# test-vector-3-nonce112.txt
check(128, 128, 112, "CA8AFCA031BAC3F480A583BD6C50A547")
check(192, 128, 112, "D170C1DF356308079DA9A3F619147148")
check(256, 128, 112, "57F94381F2F9231EFB04AECD323757C3")
check(128, 96, 112, "3A618B2531ED39F260C750DC")
check(192, 96, 112, "9071EB89FEDBADDA88FD286E")
check(256, 96, 112, "FDF0EFB97F21A39AC4BAB5AC")
check(128, 64, 112, "FAB2FF3A8DD82A13")
check(192, 64, 112, "AC01D912BD0737D3")
check(256, 64, 112, "9D1FD0B500EA4ECF")
# test-vector-3-nonce120.txt
check(128, 128, 120, "9E043A7140A25FB91F43BCC9DD7E0F46")
check(192, 128, 120, "680000E53908323A7F396B955B8EC641")
check(256, 128, 120, "8304B97FAACDA56E676602E1878A7E6F")
check(128, 96, 120, "81F978AC9867E825D339847D")
check(192, 96, 120, "EFCF2D60B24926ADA48CF5B1")
check(256, 96, 120, "84961DC56E917B165E58C174")
check(128, 64, 120, "227AEE6C9D905A61")
check(192, 64, 120, "541DE691B9E1A2F9")
check(256, 64, 120, "B0E761381C7129FC")
def test_2_bugfix(self):
nonce = unhexlify("EEDDCCBBAA9988776655443322110D")
key = unhexlify("0F0E0D0C0B0A09080706050403020100")
A = unhexlify("000102030405060708090A0B0C0D0E0F1011121314151617"
"18191A1B1C1D1E1F2021222324252627")
P = unhexlify("000102030405060708090A0B0C0D0E0F1011121314151617"
"18191A1B1C1D1E1F2021222324252627")
C = unhexlify("07E903BFC49552411ABC865F5ECE60F6FAD1F5A9F14D3070"
"FA2F1308A563207FFE14C1EEA44B22059C7484319D8A2C53"
"C236A7B3")
mac_len = len(C) - len(P)
# Prior to version 3.17, a nonce of maximum length (15 bytes)
# was actually used as a 14 byte nonce. The last byte was erroneously
# ignored.
buggy_result = unhexlify("BA015C4E5AE54D76C890AE81BD40DC57"
"03EDC30E8AC2A58BC5D8FA4D61C5BAE6"
"C39BEAC435B2FD56A2A5085C1B135D77"
"0C8264B7")
cipher = AES.new(key, AES.MODE_OCB, nonce=nonce[:-1], mac_len=mac_len)
cipher.update(A)
C_out2, tag_out2 = cipher.encrypt_and_digest(P)
self.assertEqual(buggy_result, C_out2 + tag_out2)
def get_tests(config={}):
tests = []
tests += list_test_cases(OcbTests)
tests += list_test_cases(OcbFSMTests)
tests += list_test_cases(OcbRfc7253Test)
tests += list_test_cases(OcbDkgTest)
return tests
if __name__ == '__main__':
def suite():
return unittest.TestSuite(get_tests())
unittest.main(defaultTest='suite')
PK ! G$ $ Cipher/test_OFB.pynu [ # ===================================================================
#
# Copyright (c) 2015, Legrandin
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ===================================================================
import unittest
from binascii import unhexlify
from Crypto.SelfTest.st_common import list_test_cases
from Crypto.Util.py3compat import tobytes
from Crypto.Cipher import AES, DES3, DES
from Crypto.Hash import SHAKE128
from Crypto.SelfTest.loader import load_test_vectors_wycheproof
def get_tag_random(tag, length):
return SHAKE128.new(data=tobytes(tag)).read(length)
from Crypto.SelfTest.Cipher.test_CBC import BlockChainingTests
class OfbTests(BlockChainingTests):
aes_mode = AES.MODE_OFB
des3_mode = DES3.MODE_OFB
# Redefine test_unaligned_data_128/64
def test_unaligned_data_128(self):
plaintexts = [ b"7777777" ] * 100
cipher = AES.new(self.key_128, AES.MODE_CFB, self.iv_128, segment_size=8)
ciphertexts = [ cipher.encrypt(x) for x in plaintexts ]
cipher = AES.new(self.key_128, AES.MODE_CFB, self.iv_128, segment_size=8)
self.assertEqual(b"".join(ciphertexts), cipher.encrypt(b"".join(plaintexts)))
cipher = AES.new(self.key_128, AES.MODE_CFB, self.iv_128, segment_size=128)
ciphertexts = [ cipher.encrypt(x) for x in plaintexts ]
cipher = AES.new(self.key_128, AES.MODE_CFB, self.iv_128, segment_size=128)
self.assertEqual(b"".join(ciphertexts), cipher.encrypt(b"".join(plaintexts)))
def test_unaligned_data_64(self):
plaintexts = [ b"7777777" ] * 100
cipher = DES3.new(self.key_192, DES3.MODE_CFB, self.iv_64, segment_size=8)
ciphertexts = [ cipher.encrypt(x) for x in plaintexts ]
cipher = DES3.new(self.key_192, DES3.MODE_CFB, self.iv_64, segment_size=8)
self.assertEqual(b"".join(ciphertexts), cipher.encrypt(b"".join(plaintexts)))
cipher = DES3.new(self.key_192, DES3.MODE_CFB, self.iv_64, segment_size=64)
ciphertexts = [ cipher.encrypt(x) for x in plaintexts ]
cipher = DES3.new(self.key_192, DES3.MODE_CFB, self.iv_64, segment_size=64)
self.assertEqual(b"".join(ciphertexts), cipher.encrypt(b"".join(plaintexts)))
from Crypto.SelfTest.Cipher.test_CBC import NistBlockChainingVectors
class NistOfbVectors(NistBlockChainingVectors):
aes_mode = AES.MODE_OFB
des_mode = DES.MODE_OFB
des3_mode = DES3.MODE_OFB
# Create one test method per file
nist_aes_kat_mmt_files = (
# KAT
"OFBGFSbox128.rsp",
"OFBGFSbox192.rsp",
"OFBGFSbox256.rsp",
"OFBKeySbox128.rsp",
"OFBKeySbox192.rsp",
"OFBKeySbox256.rsp",
"OFBVarKey128.rsp",
"OFBVarKey192.rsp",
"OFBVarKey256.rsp",
"OFBVarTxt128.rsp",
"OFBVarTxt192.rsp",
"OFBVarTxt256.rsp",
# MMT
"OFBMMT128.rsp",
"OFBMMT192.rsp",
"OFBMMT256.rsp",
)
nist_aes_mct_files = (
"OFBMCT128.rsp",
"OFBMCT192.rsp",
"OFBMCT256.rsp",
)
for file_name in nist_aes_kat_mmt_files:
def new_func(self, file_name=file_name):
self._do_kat_aes_test(file_name)
setattr(NistOfbVectors, "test_AES_" + file_name, new_func)
for file_name in nist_aes_mct_files:
def new_func(self, file_name=file_name):
self._do_mct_aes_test(file_name)
setattr(NistOfbVectors, "test_AES_" + file_name, new_func)
del file_name, new_func
nist_tdes_files = (
"TOFBMMT2.rsp", # 2TDES
"TOFBMMT3.rsp", # 3TDES
"TOFBinvperm.rsp", # Single DES
"TOFBpermop.rsp",
"TOFBsubtab.rsp",
"TOFBvarkey.rsp",
"TOFBvartext.rsp",
)
for file_name in nist_tdes_files:
def new_func(self, file_name=file_name):
self._do_tdes_test(file_name)
setattr(NistOfbVectors, "test_TDES_" + file_name, new_func)
# END OF NIST OFB TEST VECTORS
class SP800TestVectors(unittest.TestCase):
"""Class exercising the OFB test vectors found in Section F.4
of NIST SP 800-3A"""
def test_aes_128(self):
plaintext = '6bc1bee22e409f96e93d7e117393172a' +\
'ae2d8a571e03ac9c9eb76fac45af8e51' +\
'30c81c46a35ce411e5fbc1191a0a52ef' +\
'f69f2445df4f9b17ad2b417be66c3710'
ciphertext = '3b3fd92eb72dad20333449f8e83cfb4a' +\
'7789508d16918f03f53c52dac54ed825' +\
'9740051e9c5fecf64344f7a82260edcc' +\
'304c6528f659c77866a510d9c1d6ae5e'
key = '2b7e151628aed2a6abf7158809cf4f3c'
iv = '000102030405060708090a0b0c0d0e0f'
key = unhexlify(key)
iv = unhexlify(iv)
plaintext = unhexlify(plaintext)
ciphertext = unhexlify(ciphertext)
cipher = AES.new(key, AES.MODE_OFB, iv)
self.assertEqual(cipher.encrypt(plaintext), ciphertext)
cipher = AES.new(key, AES.MODE_OFB, iv)
self.assertEqual(cipher.decrypt(ciphertext), plaintext)
cipher = AES.new(key, AES.MODE_OFB, iv)
self.assertEqual(cipher.encrypt(plaintext[:-8]), ciphertext[:-8])
cipher = AES.new(key, AES.MODE_OFB, iv)
self.assertEqual(cipher.decrypt(ciphertext[:-8]), plaintext[:-8])
def test_aes_192(self):
plaintext = '6bc1bee22e409f96e93d7e117393172a' +\
'ae2d8a571e03ac9c9eb76fac45af8e51' +\
'30c81c46a35ce411e5fbc1191a0a52ef' +\
'f69f2445df4f9b17ad2b417be66c3710'
ciphertext = 'cdc80d6fddf18cab34c25909c99a4174' +\
'fcc28b8d4c63837c09e81700c1100401' +\
'8d9a9aeac0f6596f559c6d4daf59a5f2' +\
'6d9f200857ca6c3e9cac524bd9acc92a'
key = '8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b'
iv = '000102030405060708090a0b0c0d0e0f'
key = unhexlify(key)
iv = unhexlify(iv)
plaintext = unhexlify(plaintext)
ciphertext = unhexlify(ciphertext)
cipher = AES.new(key, AES.MODE_OFB, iv)
self.assertEqual(cipher.encrypt(plaintext), ciphertext)
cipher = AES.new(key, AES.MODE_OFB, iv)
self.assertEqual(cipher.decrypt(ciphertext), plaintext)
cipher = AES.new(key, AES.MODE_OFB, iv)
self.assertEqual(cipher.encrypt(plaintext[:-8]), ciphertext[:-8])
cipher = AES.new(key, AES.MODE_OFB, iv)
self.assertEqual(cipher.decrypt(ciphertext[:-8]), plaintext[:-8])
def test_aes_256(self):
plaintext = '6bc1bee22e409f96e93d7e117393172a' +\
'ae2d8a571e03ac9c9eb76fac45af8e51' +\
'30c81c46a35ce411e5fbc1191a0a52ef' +\
'f69f2445df4f9b17ad2b417be66c3710'
ciphertext = 'dc7e84bfda79164b7ecd8486985d3860' +\
'4febdc6740d20b3ac88f6ad82a4fb08d' +\
'71ab47a086e86eedf39d1c5bba97c408' +\
'0126141d67f37be8538f5a8be740e484'
key = '603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4'
iv = '000102030405060708090a0b0c0d0e0f'
key = unhexlify(key)
iv = unhexlify(iv)
plaintext = unhexlify(plaintext)
ciphertext = unhexlify(ciphertext)
cipher = AES.new(key, AES.MODE_OFB, iv)
self.assertEqual(cipher.encrypt(plaintext), ciphertext)
cipher = AES.new(key, AES.MODE_OFB, iv)
self.assertEqual(cipher.decrypt(ciphertext), plaintext)
cipher = AES.new(key, AES.MODE_OFB, iv)
self.assertEqual(cipher.encrypt(plaintext[:-8]), ciphertext[:-8])
cipher = AES.new(key, AES.MODE_OFB, iv)
self.assertEqual(cipher.decrypt(ciphertext[:-8]), plaintext[:-8])
def get_tests(config={}):
tests = []
tests += list_test_cases(OfbTests)
if config.get('slow_tests'):
tests += list_test_cases(NistOfbVectors)
tests += list_test_cases(SP800TestVectors)
return tests
if __name__ == '__main__':
suite = lambda: unittest.TestSuite(get_tests())
unittest.main(defaultTest='suite')
PK ! ?zw w Cipher/test_ChaCha20_Poly1305.pynu [ # ===================================================================
#
# Copyright (c) 2018, Helder Eijs
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ===================================================================
import unittest
from binascii import unhexlify
from Crypto.SelfTest.st_common import list_test_cases
from Crypto.SelfTest.loader import load_test_vectors_wycheproof
from Crypto.Util.py3compat import tobytes
from Crypto.Cipher import ChaCha20_Poly1305
from Crypto.Hash import SHAKE128
from Crypto.Util.strxor import strxor
def get_tag_random(tag, length):
return SHAKE128.new(data=tobytes(tag)).read(length)
class ChaCha20Poly1305Tests(unittest.TestCase):
key_256 = get_tag_random("key_256", 32)
nonce_96 = get_tag_random("nonce_96", 12)
data_128 = get_tag_random("data_128", 16)
def test_loopback(self):
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
pt = get_tag_random("plaintext", 16 * 100)
ct = cipher.encrypt(pt)
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
pt2 = cipher.decrypt(ct)
self.assertEqual(pt, pt2)
def test_nonce(self):
# Nonce can only be 8 or 12 bytes
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=b'H' * 8)
self.assertEqual(len(cipher.nonce), 8)
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=b'H' * 12)
self.assertEqual(len(cipher.nonce), 12)
# If not passed, the nonce is created randomly
cipher = ChaCha20_Poly1305.new(key=self.key_256)
nonce1 = cipher.nonce
cipher = ChaCha20_Poly1305.new(key=self.key_256)
nonce2 = cipher.nonce
self.assertEqual(len(nonce1), 12)
self.assertNotEqual(nonce1, nonce2)
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
ct = cipher.encrypt(self.data_128)
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
self.assertEqual(ct, cipher.encrypt(self.data_128))
def test_nonce_must_be_bytes(self):
self.assertRaises(TypeError,
ChaCha20_Poly1305.new,
key=self.key_256,
nonce=u'test12345678')
def test_nonce_length(self):
# nonce can only be 8 or 12 bytes long
self.assertRaises(ValueError,
ChaCha20_Poly1305.new,
key=self.key_256,
nonce=b'0' * 7)
self.assertRaises(ValueError,
ChaCha20_Poly1305.new,
key=self.key_256,
nonce=b'')
def test_block_size(self):
# Not based on block ciphers
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
self.assertFalse(hasattr(cipher, 'block_size'))
def test_nonce_attribute(self):
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
self.assertEqual(cipher.nonce, self.nonce_96)
# By default, a 12 bytes long nonce is randomly generated
nonce1 = ChaCha20_Poly1305.new(key=self.key_256).nonce
nonce2 = ChaCha20_Poly1305.new(key=self.key_256).nonce
self.assertEqual(len(nonce1), 12)
self.assertNotEqual(nonce1, nonce2)
def test_unknown_parameters(self):
self.assertRaises(TypeError,
ChaCha20_Poly1305.new,
key=self.key_256,
param=9)
def test_null_encryption_decryption(self):
for func in "encrypt", "decrypt":
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
result = getattr(cipher, func)(b"")
self.assertEqual(result, b"")
def test_either_encrypt_or_decrypt(self):
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
cipher.encrypt(b"")
self.assertRaises(TypeError, cipher.decrypt, b"")
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
cipher.decrypt(b"")
self.assertRaises(TypeError, cipher.encrypt, b"")
def test_data_must_be_bytes(self):
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
self.assertRaises(TypeError, cipher.encrypt, u'test1234567890-*')
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
self.assertRaises(TypeError, cipher.decrypt, u'test1234567890-*')
def test_mac_len(self):
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
_, mac = cipher.encrypt_and_digest(self.data_128)
self.assertEqual(len(mac), 16)
def test_invalid_mac(self):
from Crypto.Util.strxor import strxor_c
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
ct, mac = cipher.encrypt_and_digest(self.data_128)
invalid_mac = strxor_c(mac, 0x01)
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
self.assertRaises(ValueError, cipher.decrypt_and_verify, ct,
invalid_mac)
def test_hex_mac(self):
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
mac_hex = cipher.hexdigest()
self.assertEqual(cipher.digest(), unhexlify(mac_hex))
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
cipher.hexverify(mac_hex)
def test_message_chunks(self):
# Validate that both associated data and plaintext/ciphertext
# can be broken up in chunks of arbitrary length
auth_data = get_tag_random("authenticated data", 127)
plaintext = get_tag_random("plaintext", 127)
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
cipher.update(auth_data)
ciphertext, ref_mac = cipher.encrypt_and_digest(plaintext)
def break_up(data, chunk_length):
return [data[i:i+chunk_length] for i in range(0, len(data),
chunk_length)]
# Encryption
for chunk_length in 1, 2, 3, 7, 10, 13, 16, 40, 80, 128:
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
for chunk in break_up(auth_data, chunk_length):
cipher.update(chunk)
pt2 = b""
for chunk in break_up(ciphertext, chunk_length):
pt2 += cipher.decrypt(chunk)
self.assertEqual(plaintext, pt2)
cipher.verify(ref_mac)
# Decryption
for chunk_length in 1, 2, 3, 7, 10, 13, 16, 40, 80, 128:
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
for chunk in break_up(auth_data, chunk_length):
cipher.update(chunk)
ct2 = b""
for chunk in break_up(plaintext, chunk_length):
ct2 += cipher.encrypt(chunk)
self.assertEqual(ciphertext, ct2)
self.assertEqual(cipher.digest(), ref_mac)
def test_bytearray(self):
# Encrypt
key_ba = bytearray(self.key_256)
nonce_ba = bytearray(self.nonce_96)
header_ba = bytearray(self.data_128)
data_ba = bytearray(self.data_128)
cipher1 = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
cipher1.update(self.data_128)
ct = cipher1.encrypt(self.data_128)
tag = cipher1.digest()
cipher2 = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
key_ba[:3] = b'\xFF\xFF\xFF'
nonce_ba[:3] = b'\xFF\xFF\xFF'
cipher2.update(header_ba)
header_ba[:3] = b'\xFF\xFF\xFF'
ct_test = cipher2.encrypt(data_ba)
data_ba[:3] = b'\x99\x99\x99'
tag_test = cipher2.digest()
self.assertEqual(ct, ct_test)
self.assertEqual(tag, tag_test)
self.assertEqual(cipher1.nonce, cipher2.nonce)
# Decrypt
key_ba = bytearray(self.key_256)
nonce_ba = bytearray(self.nonce_96)
header_ba = bytearray(self.data_128)
ct_ba = bytearray(ct)
tag_ba = bytearray(tag)
del data_ba
cipher3 = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
key_ba[:3] = b'\xFF\xFF\xFF'
nonce_ba[:3] = b'\xFF\xFF\xFF'
cipher3.update(header_ba)
header_ba[:3] = b'\xFF\xFF\xFF'
pt_test = cipher3.decrypt(ct_ba)
ct_ba[:3] = b'\xFF\xFF\xFF'
cipher3.verify(tag_ba)
self.assertEqual(pt_test, self.data_128)
def test_memoryview(self):
# Encrypt
key_mv = memoryview(bytearray(self.key_256))
nonce_mv = memoryview(bytearray(self.nonce_96))
header_mv = memoryview(bytearray(self.data_128))
data_mv = memoryview(bytearray(self.data_128))
cipher1 = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
cipher1.update(self.data_128)
ct = cipher1.encrypt(self.data_128)
tag = cipher1.digest()
cipher2 = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
key_mv[:3] = b'\xFF\xFF\xFF'
nonce_mv[:3] = b'\xFF\xFF\xFF'
cipher2.update(header_mv)
header_mv[:3] = b'\xFF\xFF\xFF'
ct_test = cipher2.encrypt(data_mv)
data_mv[:3] = b'\x99\x99\x99'
tag_test = cipher2.digest()
self.assertEqual(ct, ct_test)
self.assertEqual(tag, tag_test)
self.assertEqual(cipher1.nonce, cipher2.nonce)
# Decrypt
key_mv = memoryview(bytearray(self.key_256))
nonce_mv = memoryview(bytearray(self.nonce_96))
header_mv = memoryview(bytearray(self.data_128))
ct_mv = memoryview(bytearray(ct))
tag_mv = memoryview(bytearray(tag))
del data_mv
cipher3 = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
key_mv[:3] = b'\xFF\xFF\xFF'
nonce_mv[:3] = b'\xFF\xFF\xFF'
cipher3.update(header_mv)
header_mv[:3] = b'\xFF\xFF\xFF'
pt_test = cipher3.decrypt(ct_mv)
ct_mv[:3] = b'\x99\x99\x99'
cipher3.verify(tag_mv)
self.assertEqual(pt_test, self.data_128)
class XChaCha20Poly1305Tests(unittest.TestCase):
def test_nonce(self):
# Nonce can only be 24 bytes
cipher = ChaCha20_Poly1305.new(key=b'Y' * 32,
nonce=b'H' * 24)
self.assertEqual(len(cipher.nonce), 24)
self.assertEqual(cipher.nonce, b'H' * 24)
def test_encrypt(self):
# From https://tools.ietf.org/html/draft-arciszewski-xchacha-03
# Section A.3.1
pt = b"""
4c616469657320616e642047656e746c656d656e206f662074686520636c6173
73206f66202739393a204966204920636f756c64206f6666657220796f75206f
6e6c79206f6e652074697020666f7220746865206675747572652c2073756e73
637265656e20776f756c642062652069742e"""
pt = unhexlify(pt.replace(b"\n", b"").replace(b" ", b""))
aad = unhexlify(b"50515253c0c1c2c3c4c5c6c7")
key = unhexlify(b"808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f")
iv = unhexlify(b"404142434445464748494a4b4c4d4e4f5051525354555657")
ct = b"""
bd6d179d3e83d43b9576579493c0e939572a1700252bfaccbed2902c21396cbb
731c7f1b0b4aa6440bf3a82f4eda7e39ae64c6708c54c216cb96b72e1213b452
2f8c9ba40db5d945b11b69b982c1bb9e3f3fac2bc369488f76b2383565d3fff9
21f9664c97637da9768812f615c68b13b52e"""
ct = unhexlify(ct.replace(b"\n", b"").replace(b" ", b""))
tag = unhexlify(b"c0875924c1c7987947deafd8780acf49")
cipher = ChaCha20_Poly1305.new(key=key, nonce=iv)
cipher.update(aad)
ct_test, tag_test = cipher.encrypt_and_digest(pt)
self.assertEqual(ct, ct_test)
self.assertEqual(tag, tag_test)
cipher = ChaCha20_Poly1305.new(key=key, nonce=iv)
cipher.update(aad)
cipher.decrypt_and_verify(ct, tag)
class ChaCha20Poly1305FSMTests(unittest.TestCase):
key_256 = get_tag_random("key_256", 32)
nonce_96 = get_tag_random("nonce_96", 12)
data_128 = get_tag_random("data_128", 16)
def test_valid_init_encrypt_decrypt_digest_verify(self):
# No authenticated data, fixed plaintext
# Verify path INIT->ENCRYPT->DIGEST
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
ct = cipher.encrypt(self.data_128)
mac = cipher.digest()
# Verify path INIT->DECRYPT->VERIFY
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
cipher.decrypt(ct)
cipher.verify(mac)
def test_valid_init_update_digest_verify(self):
# No plaintext, fixed authenticated data
# Verify path INIT->UPDATE->DIGEST
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
cipher.update(self.data_128)
mac = cipher.digest()
# Verify path INIT->UPDATE->VERIFY
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
cipher.update(self.data_128)
cipher.verify(mac)
def test_valid_full_path(self):
# Fixed authenticated data, fixed plaintext
# Verify path INIT->UPDATE->ENCRYPT->DIGEST
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
cipher.update(self.data_128)
ct = cipher.encrypt(self.data_128)
mac = cipher.digest()
# Verify path INIT->UPDATE->DECRYPT->VERIFY
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
cipher.update(self.data_128)
cipher.decrypt(ct)
cipher.verify(mac)
def test_valid_init_digest(self):
# Verify path INIT->DIGEST
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
cipher.digest()
def test_valid_init_verify(self):
# Verify path INIT->VERIFY
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
mac = cipher.digest()
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
cipher.verify(mac)
def test_valid_multiple_encrypt_or_decrypt(self):
for method_name in "encrypt", "decrypt":
for auth_data in (None, b"333", self.data_128,
self.data_128 + b"3"):
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
if auth_data is not None:
cipher.update(auth_data)
method = getattr(cipher, method_name)
method(self.data_128)
method(self.data_128)
method(self.data_128)
method(self.data_128)
def test_valid_multiple_digest_or_verify(self):
# Multiple calls to digest
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
cipher.update(self.data_128)
first_mac = cipher.digest()
for x in range(4):
self.assertEqual(first_mac, cipher.digest())
# Multiple calls to verify
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
cipher.update(self.data_128)
for x in range(5):
cipher.verify(first_mac)
def test_valid_encrypt_and_digest_decrypt_and_verify(self):
# encrypt_and_digest
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
cipher.update(self.data_128)
ct, mac = cipher.encrypt_and_digest(self.data_128)
# decrypt_and_verify
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
cipher.update(self.data_128)
pt = cipher.decrypt_and_verify(ct, mac)
self.assertEqual(self.data_128, pt)
def test_invalid_mixing_encrypt_decrypt(self):
# Once per method, with or without assoc. data
for method1_name, method2_name in (("encrypt", "decrypt"),
("decrypt", "encrypt")):
for assoc_data_present in (True, False):
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
if assoc_data_present:
cipher.update(self.data_128)
getattr(cipher, method1_name)(self.data_128)
self.assertRaises(TypeError, getattr(cipher, method2_name),
self.data_128)
def test_invalid_encrypt_or_update_after_digest(self):
for method_name in "encrypt", "update":
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
cipher.encrypt(self.data_128)
cipher.digest()
self.assertRaises(TypeError, getattr(cipher, method_name),
self.data_128)
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
cipher.encrypt_and_digest(self.data_128)
def test_invalid_decrypt_or_update_after_verify(self):
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
ct = cipher.encrypt(self.data_128)
mac = cipher.digest()
for method_name in "decrypt", "update":
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
cipher.decrypt(ct)
cipher.verify(mac)
self.assertRaises(TypeError, getattr(cipher, method_name),
self.data_128)
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
cipher.decrypt(ct)
cipher.verify(mac)
self.assertRaises(TypeError, getattr(cipher, method_name),
self.data_128)
cipher = ChaCha20_Poly1305.new(key=self.key_256,
nonce=self.nonce_96)
cipher.decrypt_and_verify(ct, mac)
self.assertRaises(TypeError, getattr(cipher, method_name),
self.data_128)
def compact(x):
return unhexlify(x.replace(" ", "").replace(":", ""))
class TestVectorsRFC(unittest.TestCase):
"""Test cases from RFC7539"""
# AAD, PT, CT, MAC, KEY, NONCE
test_vectors_hex = [
( '50 51 52 53 c0 c1 c2 c3 c4 c5 c6 c7',
'4c 61 64 69 65 73 20 61 6e 64 20 47 65 6e 74 6c'
'65 6d 65 6e 20 6f 66 20 74 68 65 20 63 6c 61 73'
'73 20 6f 66 20 27 39 39 3a 20 49 66 20 49 20 63'
'6f 75 6c 64 20 6f 66 66 65 72 20 79 6f 75 20 6f'
'6e 6c 79 20 6f 6e 65 20 74 69 70 20 66 6f 72 20'
'74 68 65 20 66 75 74 75 72 65 2c 20 73 75 6e 73'
'63 72 65 65 6e 20 77 6f 75 6c 64 20 62 65 20 69'
'74 2e',
'd3 1a 8d 34 64 8e 60 db 7b 86 af bc 53 ef 7e c2'
'a4 ad ed 51 29 6e 08 fe a9 e2 b5 a7 36 ee 62 d6'
'3d be a4 5e 8c a9 67 12 82 fa fb 69 da 92 72 8b'
'1a 71 de 0a 9e 06 0b 29 05 d6 a5 b6 7e cd 3b 36'
'92 dd bd 7f 2d 77 8b 8c 98 03 ae e3 28 09 1b 58'
'fa b3 24 e4 fa d6 75 94 55 85 80 8b 48 31 d7 bc'
'3f f4 de f0 8e 4b 7a 9d e5 76 d2 65 86 ce c6 4b'
'61 16',
'1a:e1:0b:59:4f:09:e2:6a:7e:90:2e:cb:d0:60:06:91',
'80 81 82 83 84 85 86 87 88 89 8a 8b 8c 8d 8e 8f'
'90 91 92 93 94 95 96 97 98 99 9a 9b 9c 9d 9e 9f',
'07 00 00 00' + '40 41 42 43 44 45 46 47',
),
( 'f3 33 88 86 00 00 00 00 00 00 4e 91',
'49 6e 74 65 72 6e 65 74 2d 44 72 61 66 74 73 20'
'61 72 65 20 64 72 61 66 74 20 64 6f 63 75 6d 65'
'6e 74 73 20 76 61 6c 69 64 20 66 6f 72 20 61 20'
'6d 61 78 69 6d 75 6d 20 6f 66 20 73 69 78 20 6d'
'6f 6e 74 68 73 20 61 6e 64 20 6d 61 79 20 62 65'
'20 75 70 64 61 74 65 64 2c 20 72 65 70 6c 61 63'
'65 64 2c 20 6f 72 20 6f 62 73 6f 6c 65 74 65 64'
'20 62 79 20 6f 74 68 65 72 20 64 6f 63 75 6d 65'
'6e 74 73 20 61 74 20 61 6e 79 20 74 69 6d 65 2e'
'20 49 74 20 69 73 20 69 6e 61 70 70 72 6f 70 72'
'69 61 74 65 20 74 6f 20 75 73 65 20 49 6e 74 65'
'72 6e 65 74 2d 44 72 61 66 74 73 20 61 73 20 72'
'65 66 65 72 65 6e 63 65 20 6d 61 74 65 72 69 61'
'6c 20 6f 72 20 74 6f 20 63 69 74 65 20 74 68 65'
'6d 20 6f 74 68 65 72 20 74 68 61 6e 20 61 73 20'
'2f e2 80 9c 77 6f 72 6b 20 69 6e 20 70 72 6f 67'
'72 65 73 73 2e 2f e2 80 9d',
'64 a0 86 15 75 86 1a f4 60 f0 62 c7 9b e6 43 bd'
'5e 80 5c fd 34 5c f3 89 f1 08 67 0a c7 6c 8c b2'
'4c 6c fc 18 75 5d 43 ee a0 9e e9 4e 38 2d 26 b0'
'bd b7 b7 3c 32 1b 01 00 d4 f0 3b 7f 35 58 94 cf'
'33 2f 83 0e 71 0b 97 ce 98 c8 a8 4a bd 0b 94 81'
'14 ad 17 6e 00 8d 33 bd 60 f9 82 b1 ff 37 c8 55'
'97 97 a0 6e f4 f0 ef 61 c1 86 32 4e 2b 35 06 38'
'36 06 90 7b 6a 7c 02 b0 f9 f6 15 7b 53 c8 67 e4'
'b9 16 6c 76 7b 80 4d 46 a5 9b 52 16 cd e7 a4 e9'
'90 40 c5 a4 04 33 22 5e e2 82 a1 b0 a0 6c 52 3e'
'af 45 34 d7 f8 3f a1 15 5b 00 47 71 8c bc 54 6a'
'0d 07 2b 04 b3 56 4e ea 1b 42 22 73 f5 48 27 1a'
'0b b2 31 60 53 fa 76 99 19 55 eb d6 31 59 43 4e'
'ce bb 4e 46 6d ae 5a 10 73 a6 72 76 27 09 7a 10'
'49 e6 17 d9 1d 36 10 94 fa 68 f0 ff 77 98 71 30'
'30 5b ea ba 2e da 04 df 99 7b 71 4d 6c 6f 2c 29'
'a6 ad 5c b4 02 2b 02 70 9b',
'ee ad 9d 67 89 0c bb 22 39 23 36 fe a1 85 1f 38',
'1c 92 40 a5 eb 55 d3 8a f3 33 88 86 04 f6 b5 f0'
'47 39 17 c1 40 2b 80 09 9d ca 5c bc 20 70 75 c0',
'00 00 00 00 01 02 03 04 05 06 07 08',
)
]
test_vectors = [[unhexlify(x.replace(" ", "").replace(":", "")) for x in tv] for tv in test_vectors_hex]
def runTest(self):
for assoc_data, pt, ct, mac, key, nonce in self.test_vectors:
# Encrypt
cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce)
cipher.update(assoc_data)
ct2, mac2 = cipher.encrypt_and_digest(pt)
self.assertEqual(ct, ct2)
self.assertEqual(mac, mac2)
# Decrypt
cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce)
cipher.update(assoc_data)
pt2 = cipher.decrypt_and_verify(ct, mac)
self.assertEqual(pt, pt2)
class TestVectorsWycheproof(unittest.TestCase):
def __init__(self, wycheproof_warnings):
unittest.TestCase.__init__(self)
self._wycheproof_warnings = wycheproof_warnings
self._id = "None"
def load_tests(self, filename):
def filter_tag(group):
return group['tagSize'] // 8
def filter_algo(root):
return root['algorithm']
result = load_test_vectors_wycheproof(("Cipher", "wycheproof"),
filename,
"Wycheproof ChaCha20-Poly1305",
root_tag={'algo': filter_algo},
group_tag={'tag_size': filter_tag})
return result
def setUp(self):
self.tv = []
self.tv.extend(self.load_tests("chacha20_poly1305_test.json"))
self.tv.extend(self.load_tests("xchacha20_poly1305_test.json"))
def shortDescription(self):
return self._id
def warn(self, tv):
if tv.warning and self._wycheproof_warnings:
import warnings
warnings.warn("Wycheproof warning: %s (%s)" % (self._id, tv.comment))
def test_encrypt(self, tv):
self._id = "Wycheproof Encrypt %s Test #%s" % (tv.algo, tv.id)
try:
cipher = ChaCha20_Poly1305.new(key=tv.key, nonce=tv.iv)
except ValueError as e:
assert len(tv.iv) not in (8, 12) and "Nonce must be" in str(e)
return
cipher.update(tv.aad)
ct, tag = cipher.encrypt_and_digest(tv.msg)
if tv.valid:
self.assertEqual(ct, tv.ct)
self.assertEqual(tag, tv.tag)
self.warn(tv)
def test_decrypt(self, tv):
self._id = "Wycheproof Decrypt %s Test #%s" % (tv.algo, tv.id)
try:
cipher = ChaCha20_Poly1305.new(key=tv.key, nonce=tv.iv)
except ValueError as e:
assert len(tv.iv) not in (8, 12) and "Nonce must be" in str(e)
return
cipher.update(tv.aad)
try:
pt = cipher.decrypt_and_verify(tv.ct, tv.tag)
except ValueError:
assert not tv.valid
else:
assert tv.valid
self.assertEqual(pt, tv.msg)
self.warn(tv)
def test_corrupt_decrypt(self, tv):
self._id = "Wycheproof Corrupt Decrypt ChaCha20-Poly1305 Test #" + str(tv.id)
if len(tv.iv) == 0 or len(tv.ct) < 1:
return
cipher = ChaCha20_Poly1305.new(key=tv.key, nonce=tv.iv)
cipher.update(tv.aad)
ct_corrupt = strxor(tv.ct, b"\x00" * (len(tv.ct) - 1) + b"\x01")
self.assertRaises(ValueError, cipher.decrypt_and_verify, ct_corrupt, tv.tag)
def runTest(self):
for tv in self.tv:
self.test_encrypt(tv)
self.test_decrypt(tv)
self.test_corrupt_decrypt(tv)
class TestOutput(unittest.TestCase):
def runTest(self):
# Encrypt/Decrypt data and test output parameter
key = b'4' * 32
nonce = b'5' * 12
cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce)
pt = b'5' * 16
ct = cipher.encrypt(pt)
output = bytearray(16)
cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce)
res = cipher.encrypt(pt, output=output)
self.assertEqual(ct, output)
self.assertEqual(res, None)
cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce)
res = cipher.decrypt(ct, output=output)
self.assertEqual(pt, output)
self.assertEqual(res, None)
output = memoryview(bytearray(16))
cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce)
cipher.encrypt(pt, output=output)
self.assertEqual(ct, output)
cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce)
cipher.decrypt(ct, output=output)
self.assertEqual(pt, output)
cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce)
self.assertRaises(TypeError, cipher.encrypt, pt, output=b'0'*16)
cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce)
self.assertRaises(TypeError, cipher.decrypt, ct, output=b'0'*16)
shorter_output = bytearray(7)
cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce)
self.assertRaises(ValueError, cipher.encrypt, pt, output=shorter_output)
cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce)
self.assertRaises(ValueError, cipher.decrypt, ct, output=shorter_output)
def get_tests(config={}):
wycheproof_warnings = config.get('wycheproof_warnings')
tests = []
tests += list_test_cases(ChaCha20Poly1305Tests)
tests += list_test_cases(XChaCha20Poly1305Tests)
tests += list_test_cases(ChaCha20Poly1305FSMTests)
tests += [TestVectorsRFC()]
tests += [TestVectorsWycheproof(wycheproof_warnings)]
tests += [TestOutput()]
return tests
if __name__ == '__main__':
def suite():
unittest.TestSuite(get_tests())
unittest.main(defaultTest='suite')
PK ! ޱF+ F+ / Cipher/__pycache__/test_OpenPGP.cpython-311.pycnu [
i! d dl Z d dlmZ d dlmZ d dlmZ d dlmZm Z m
Z
d dlmZ d Z
d dlmZ G d d
e Z G d de j Zi fd
Zedk rd Z e j d dS dS ) N) unhexlify)list_test_cases)tobytes)AESDES3DES)SHAKE128c l t j t | | S )N)data)r newr read)taglengths /builddir/build/BUILD/imunify360-venv-2.6.2/opt/imunify360/venv/lib64/python3.11/site-packages/Crypto/SelfTest/Cipher/test_OpenPGP.pyget_tag_randomr ' s)