Debian Codegraph @

lib/Crypto/SelfTest/Cipher/test_CBC.py

raw symbols SCIP
1 # ===================================================================
2 #
3 # Copyright (c) 2014, Legrandin <[email protected]>
4 # All rights reserved.
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions
8 # are met:
9 #
10 # 1. Redistributions of source code must retain the above copyright
11 # notice, this list of conditions and the following disclaimer.
12 # 2. Redistributions in binary form must reproduce the above copyright
13 # notice, this list of conditions and the following disclaimer in
14 # the documentation and/or other materials provided with the
15 # distribution.
16 #
17 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
20 # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
21 # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
23 # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25 # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
27 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 # POSSIBILITY OF SUCH DAMAGE.
29 # ===================================================================
30
31 import unittest
32 from binascii import unhexlify
33
34 from Crypto.SelfTest.loader import load_test_vectors
35 from Crypto.SelfTest.st_common import list_test_cases
36 from Crypto.Util.py3compat import tobytes, is_string
37 from Crypto.Cipher import AES, DES3, DES
38 from Crypto.Hash import SHAKE128
39
40
41 def get_tag_random(tag, length):
42 return SHAKE128.new(data=tobytes(tag)).read(length)
43
44 class BlockChainingTests(unittest.TestCase):
45
46 key_128 = get_tag_random("key_128", 16)
47 key_192 = get_tag_random("key_192", 24)
48 iv_128 = get_tag_random("iv_128", 16)
49 iv_64 = get_tag_random("iv_64", 8)
50 data_128 = get_tag_random("data_128", 16)
51
52 def test_loopback_128(self):
53 cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
54 pt = get_tag_random("plaintext", 16 * 100)
55 ct = cipher.encrypt(pt)
56
57 cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
58 pt2 = cipher.decrypt(ct)
59 self.assertEqual(pt, pt2)
60
61 def test_loopback_64(self):
62 cipher = DES3.new(self.key_192, self.des3_mode, self.iv_64)
63 pt = get_tag_random("plaintext", 8 * 100)
64 ct = cipher.encrypt(pt)
65
66 cipher = DES3.new(self.key_192, self.des3_mode, self.iv_64)
67 pt2 = cipher.decrypt(ct)
68 self.assertEqual(pt, pt2)
69
70 def test_iv(self):
71 # If not passed, the iv is created randomly
72 cipher = AES.new(self.key_128, self.aes_mode)
73 iv1 = cipher.iv
74 cipher = AES.new(self.key_128, self.aes_mode)
75 iv2 = cipher.iv
76 self.assertNotEqual(iv1, iv2)
77 self.assertEqual(len(iv1), 16)
78
79 # IV can be passed in uppercase or lowercase
80 cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
81 ct = cipher.encrypt(self.data_128)
82
83 cipher = AES.new(self.key_128, self.aes_mode, iv=self.iv_128)
84 self.assertEqual(ct, cipher.encrypt(self.data_128))
85
86 cipher = AES.new(self.key_128, self.aes_mode, IV=self.iv_128)
87 self.assertEqual(ct, cipher.encrypt(self.data_128))
88
89 def test_iv_must_be_bytes(self):
90 self.assertRaises(TypeError, AES.new, self.key_128, self.aes_mode,
91 iv = u'test1234567890-*')
92
93 def test_only_one_iv(self):
94 # Only one IV/iv keyword allowed
95 self.assertRaises(TypeError, AES.new, self.key_128, self.aes_mode,
96 iv=self.iv_128, IV=self.iv_128)
97
98 def test_iv_with_matching_length(self):
99 self.assertRaises(ValueError, AES.new, self.key_128, self.aes_mode,
100 b"")
101 self.assertRaises(ValueError, AES.new, self.key_128, self.aes_mode,
102 self.iv_128[:15])
103 self.assertRaises(ValueError, AES.new, self.key_128, self.aes_mode,
104 self.iv_128 + b"0")
105
106 def test_block_size_128(self):
107 cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
108 self.assertEqual(cipher.block_size, AES.block_size)
109
110 def test_block_size_64(self):
111 cipher = DES3.new(self.key_192, self.des3_mode, self.iv_64)
112 self.assertEqual(cipher.block_size, DES3.block_size)
113
114 def test_unaligned_data_128(self):
115 cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
116 for wrong_length in range(1,16):
117 self.assertRaises(ValueError, cipher.encrypt, b"5" * wrong_length)
118
119 cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
120 for wrong_length in range(1,16):
121 self.assertRaises(ValueError, cipher.decrypt, b"5" * wrong_length)
122
123 def test_unaligned_data_64(self):
124 cipher = DES3.new(self.key_192, self.des3_mode, self.iv_64)
125 for wrong_length in range(1,8):
126 self.assertRaises(ValueError, cipher.encrypt, b"5" * wrong_length)
127
128 cipher = DES3.new(self.key_192, self.des3_mode, self.iv_64)
129 for wrong_length in range(1,8):
130 self.assertRaises(ValueError, cipher.decrypt, b"5" * wrong_length)
131
132 def test_IV_iv_attributes(self):
133 data = get_tag_random("data", 16 * 100)
134 for func in "encrypt", "decrypt":
135 cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
136 getattr(cipher, func)(data)
137 self.assertEqual(cipher.iv, self.iv_128)
138 self.assertEqual(cipher.IV, self.iv_128)
139
140 def test_unknown_parameters(self):
141 self.assertRaises(TypeError, AES.new, self.key_128, self.aes_mode,
142 self.iv_128, 7)
143 self.assertRaises(TypeError, AES.new, self.key_128, self.aes_mode,
144 iv=self.iv_128, unknown=7)
145 # But some are only known by the base cipher (e.g. use_aesni consumed by the AES module)
146 AES.new(self.key_128, self.aes_mode, iv=self.iv_128, use_aesni=False)
147
148 def test_null_encryption_decryption(self):
149 for func in "encrypt", "decrypt":
150 cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
151 result = getattr(cipher, func)(b"")
152 self.assertEqual(result, b"")
153
154 def test_either_encrypt_or_decrypt(self):
155 cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
156 cipher.encrypt(b"")
157 self.assertRaises(TypeError, cipher.decrypt, b"")
158
159 cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
160 cipher.decrypt(b"")
161 self.assertRaises(TypeError, cipher.encrypt, b"")
162
163 def test_data_must_be_bytes(self):
164 cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
165 self.assertRaises(TypeError, cipher.encrypt, u'test1234567890-*')
166
167 cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
168 self.assertRaises(TypeError, cipher.decrypt, u'test1234567890-*')
169
170 def test_bytearray(self):
171 data = b"1" * 128
172 data_ba = bytearray(data)
173
174 # Encrypt
175 key_ba = bytearray(self.key_128)
176 iv_ba = bytearray(self.iv_128)
177
178 cipher1 = AES.new(self.key_128, self.aes_mode, self.iv_128)
179 ref1 = cipher1.encrypt(data)
180
181 cipher2 = AES.new(key_ba, self.aes_mode, iv_ba)
182 key_ba[:3] = b'\xFF\xFF\xFF'
183 iv_ba[:3] = b'\xFF\xFF\xFF'
184 ref2 = cipher2.encrypt(data_ba)
185
186 self.assertEqual(ref1, ref2)
187 self.assertEqual(cipher1.iv, cipher2.iv)
188
189 # Decrypt
190 key_ba = bytearray(self.key_128)
191 iv_ba = bytearray(self.iv_128)
192
193 cipher3 = AES.new(self.key_128, self.aes_mode, self.iv_128)
194 ref3 = cipher3.decrypt(data)
195
196 cipher4 = AES.new(key_ba, self.aes_mode, iv_ba)
197 key_ba[:3] = b'\xFF\xFF\xFF'
198 iv_ba[:3] = b'\xFF\xFF\xFF'
199 ref4 = cipher4.decrypt(data_ba)
200
201 self.assertEqual(ref3, ref4)
202
203 def test_memoryview(self):
204 data = b"1" * 128
205 data_mv = memoryview(bytearray(data))
206
207 # Encrypt
208 key_mv = memoryview(bytearray(self.key_128))
209 iv_mv = memoryview(bytearray(self.iv_128))
210
211 cipher1 = AES.new(self.key_128, self.aes_mode, self.iv_128)
212 ref1 = cipher1.encrypt(data)
213
214 cipher2 = AES.new(key_mv, self.aes_mode, iv_mv)
215 key_mv[:3] = b'\xFF\xFF\xFF'
216 iv_mv[:3] = b'\xFF\xFF\xFF'
217 ref2 = cipher2.encrypt(data_mv)
218
219 self.assertEqual(ref1, ref2)
220 self.assertEqual(cipher1.iv, cipher2.iv)
221
222 # Decrypt
223 key_mv = memoryview(bytearray(self.key_128))
224 iv_mv = memoryview(bytearray(self.iv_128))
225
226 cipher3 = AES.new(self.key_128, self.aes_mode, self.iv_128)
227 ref3 = cipher3.decrypt(data)
228
229 cipher4 = AES.new(key_mv, self.aes_mode, iv_mv)
230 key_mv[:3] = b'\xFF\xFF\xFF'
231 iv_mv[:3] = b'\xFF\xFF\xFF'
232 ref4 = cipher4.decrypt(data_mv)
233
234 self.assertEqual(ref3, ref4)
235
236 def test_output_param(self):
237
238 pt = b'5' * 128
239 cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
240 ct = cipher.encrypt(pt)
241
242 output = bytearray(128)
243 cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
244 res = cipher.encrypt(pt, output=output)
245 self.assertEqual(ct, output)
246 self.assertEqual(res, None)
247
248 cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
249 res = cipher.decrypt(ct, output=output)
250 self.assertEqual(pt, output)
251 self.assertEqual(res, None)
252
253
254 def test_output_param_same_buffer(self):
255
256 pt = b'5' * 128
257 cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
258 ct = cipher.encrypt(pt)
259
260 pt_ba = bytearray(pt)
261 cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
262 res = cipher.encrypt(pt_ba, output=pt_ba)
263 self.assertEqual(ct, pt_ba)
264 self.assertEqual(res, None)
265
266 ct_ba = bytearray(ct)
267 cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
268 res = cipher.decrypt(ct_ba, output=ct_ba)
269 self.assertEqual(pt, ct_ba)
270 self.assertEqual(res, None)
271
272
273 def test_output_param_memoryview(self):
274
275 pt = b'5' * 128
276 cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
277 ct = cipher.encrypt(pt)
278
279 output = memoryview(bytearray(128))
280 cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
281 cipher.encrypt(pt, output=output)
282 self.assertEqual(ct, output)
283
284 cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
285 cipher.decrypt(ct, output=output)
286 self.assertEqual(pt, output)
287
288 def test_output_param_neg(self):
289 LEN_PT = 128
290
291 pt = b'5' * LEN_PT
292 cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
293 ct = cipher.encrypt(pt)
294
295 cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
296 self.assertRaises(TypeError, cipher.encrypt, pt, output=b'0' * LEN_PT)
297
298 cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
299 self.assertRaises(TypeError, cipher.decrypt, ct, output=b'0' * LEN_PT)
300
301 shorter_output = bytearray(LEN_PT - 1)
302 cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
303 self.assertRaises(ValueError, cipher.encrypt, pt, output=shorter_output)
304 cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
305 self.assertRaises(ValueError, cipher.decrypt, ct, output=shorter_output)
306
307
308 class CbcTests(BlockChainingTests):
309 aes_mode = AES.MODE_CBC
310 des3_mode = DES3.MODE_CBC
311
312
313 class NistBlockChainingVectors(unittest.TestCase):
314
315 def _do_kat_aes_test(self, file_name):
316
317 test_vectors = load_test_vectors(("Cipher", "AES"),
318 file_name,
319 "AES CBC KAT",
320 { "count" : lambda x: int(x) } )
321 if test_vectors is None:
322 return
323
324 direction = None
325 for tv in test_vectors:
326
327 # The test vector file contains some directive lines
328 if is_string(tv):
329 direction = tv
330 continue
331
332 self.description = tv.desc
333
334 cipher = AES.new(tv.key, self.aes_mode, tv.iv)
335 if direction == "[ENCRYPT]":
336 self.assertEqual(cipher.encrypt(tv.plaintext), tv.ciphertext)
337 elif direction == "[DECRYPT]":
338 self.assertEqual(cipher.decrypt(tv.ciphertext), tv.plaintext)
339 else:
340 assert False
341
342 # See Section 6.4.2 in AESAVS
343 def _do_mct_aes_test(self, file_name):
344
345 test_vectors = load_test_vectors(("Cipher", "AES"),
346 file_name,
347 "AES CBC Montecarlo",
348 { "count" : lambda x: int(x) } )
349 if test_vectors is None:
350 return
351
352 direction = None
353 for tv in test_vectors:
354
355 # The test vector file contains some directive lines
356 if is_string(tv):
357 direction = tv
358 continue
359
360 self.description = tv.desc
361 cipher = AES.new(tv.key, self.aes_mode, tv.iv)
362
363 if direction == '[ENCRYPT]':
364 cts = [ tv.iv ]
365 for count in range(1000):
366 cts.append(cipher.encrypt(tv.plaintext))
367 tv.plaintext = cts[-2]
368 self.assertEqual(cts[-1], tv.ciphertext)
369 elif direction == '[DECRYPT]':
370 pts = [ tv.iv]
371 for count in range(1000):
372 pts.append(cipher.decrypt(tv.ciphertext))
373 tv.ciphertext = pts[-2]
374 self.assertEqual(pts[-1], tv.plaintext)
375 else:
376 assert False
377
378 def _do_tdes_test(self, file_name):
379
380 test_vectors = load_test_vectors(("Cipher", "TDES"),
381 file_name,
382 "TDES CBC KAT",
383 { "count" : lambda x: int(x) } )
384 if test_vectors is None:
385 return
386
387 direction = None
388 for tv in test_vectors:
389
390 # The test vector file contains some directive lines
391 if is_string(tv):
392 direction = tv
393 continue
394
395 self.description = tv.desc
396 if hasattr(tv, "keys"):
397 cipher = DES.new(tv.keys, self.des_mode, tv.iv)
398 else:
399 if tv.key1 != tv.key3:
400 key = tv.key1 + tv.key2 + tv.key3 # Option 3
401 else:
402 key = tv.key1 + tv.key2 # Option 2
403 cipher = DES3.new(key, self.des3_mode, tv.iv)
404
405 if direction == "[ENCRYPT]":
406 self.assertEqual(cipher.encrypt(tv.plaintext), tv.ciphertext)
407 elif direction == "[DECRYPT]":
408 self.assertEqual(cipher.decrypt(tv.ciphertext), tv.plaintext)
409 else:
410 assert False
411
412
413 class NistCbcVectors(NistBlockChainingVectors):
414 aes_mode = AES.MODE_CBC
415 des_mode = DES.MODE_CBC
416 des3_mode = DES3.MODE_CBC
417
418
419 # Create one test method per file
420 nist_aes_kat_mmt_files = (
421 # KAT
422 "CBCGFSbox128.rsp",
423 "CBCGFSbox192.rsp",
424 "CBCGFSbox256.rsp",
425 "CBCKeySbox128.rsp",
426 "CBCKeySbox192.rsp",
427 "CBCKeySbox256.rsp",
428 "CBCVarKey128.rsp",
429 "CBCVarKey192.rsp",
430 "CBCVarKey256.rsp",
431 "CBCVarTxt128.rsp",
432 "CBCVarTxt192.rsp",
433 "CBCVarTxt256.rsp",
434 # MMT
435 "CBCMMT128.rsp",
436 "CBCMMT192.rsp",
437 "CBCMMT256.rsp",
438 )
439 nist_aes_mct_files = (
440 "CBCMCT128.rsp",
441 "CBCMCT192.rsp",
442 "CBCMCT256.rsp",
443 )
444
445 for file_name in nist_aes_kat_mmt_files:
446 def new_func(self, file_name=file_name):
447 self._do_kat_aes_test(file_name)
448 setattr(NistCbcVectors, "test_AES_" + file_name, new_func)
449
450 for file_name in nist_aes_mct_files:
451 def new_func(self, file_name=file_name):
452 self._do_mct_aes_test(file_name)
453 setattr(NistCbcVectors, "test_AES_" + file_name, new_func)
454 del file_name, new_func
455
456 nist_tdes_files = (
457 "TCBCMMT2.rsp", # 2TDES
458 "TCBCMMT3.rsp", # 3TDES
459 "TCBCinvperm.rsp", # Single DES
460 "TCBCpermop.rsp",
461 "TCBCsubtab.rsp",
462 "TCBCvarkey.rsp",
463 "TCBCvartext.rsp",
464 )
465
466 for file_name in nist_tdes_files:
467 def new_func(self, file_name=file_name):
468 self._do_tdes_test(file_name)
469 setattr(NistCbcVectors, "test_TDES_" + file_name, new_func)
470
471 # END OF NIST CBC TEST VECTORS
472
473
474 class SP800TestVectors(unittest.TestCase):
475 """Class exercising the CBC test vectors found in Section F.2
476 of NIST SP 800-3A"""
477
478 def test_aes_128(self):
479 key = '2b7e151628aed2a6abf7158809cf4f3c'
480 iv = '000102030405060708090a0b0c0d0e0f'
481 plaintext = '6bc1bee22e409f96e93d7e117393172a' +\
482 'ae2d8a571e03ac9c9eb76fac45af8e51' +\
483 '30c81c46a35ce411e5fbc1191a0a52ef' +\
484 'f69f2445df4f9b17ad2b417be66c3710'
485 ciphertext = '7649abac8119b246cee98e9b12e9197d' +\
486 '5086cb9b507219ee95db113a917678b2' +\
487 '73bed6b8e3c1743b7116e69e22229516' +\
488 '3ff1caa1681fac09120eca307586e1a7'
489
490 key = unhexlify(key)
491 iv = unhexlify(iv)
492 plaintext = unhexlify(plaintext)
493 ciphertext = unhexlify(ciphertext)
494
495 cipher = AES.new(key, AES.MODE_CBC, iv)
496 self.assertEqual(cipher.encrypt(plaintext), ciphertext)
497 cipher = AES.new(key, AES.MODE_CBC, iv)
498 self.assertEqual(cipher.decrypt(ciphertext), plaintext)
499
500 def test_aes_192(self):
501 key = '8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b'
502 iv = '000102030405060708090a0b0c0d0e0f'
503 plaintext = '6bc1bee22e409f96e93d7e117393172a' +\
504 'ae2d8a571e03ac9c9eb76fac45af8e51' +\
505 '30c81c46a35ce411e5fbc1191a0a52ef' +\
506 'f69f2445df4f9b17ad2b417be66c3710'
507 ciphertext = '4f021db243bc633d7178183a9fa071e8' +\
508 'b4d9ada9ad7dedf4e5e738763f69145a' +\
509 '571b242012fb7ae07fa9baac3df102e0' +\
510 '08b0e27988598881d920a9e64f5615cd'
511
512 key = unhexlify(key)
513 iv = unhexlify(iv)
514 plaintext = unhexlify(plaintext)
515 ciphertext = unhexlify(ciphertext)
516
517 cipher = AES.new(key, AES.MODE_CBC, iv)
518 self.assertEqual(cipher.encrypt(plaintext), ciphertext)
519 cipher = AES.new(key, AES.MODE_CBC, iv)
520 self.assertEqual(cipher.decrypt(ciphertext), plaintext)
521
522 def test_aes_256(self):
523 key = '603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4'
524 iv = '000102030405060708090a0b0c0d0e0f'
525 plaintext = '6bc1bee22e409f96e93d7e117393172a' +\
526 'ae2d8a571e03ac9c9eb76fac45af8e51' +\
527 '30c81c46a35ce411e5fbc1191a0a52ef' +\
528 'f69f2445df4f9b17ad2b417be66c3710'
529 ciphertext = 'f58c4c04d6e5f1ba779eabfb5f7bfbd6' +\
530 '9cfc4e967edb808d679f777bc6702c7d' +\
531 '39f23369a9d9bacfa530e26304231461' +\
532 'b2eb05e2c39be9fcda6c19078c6a9d1b'
533
534 key = unhexlify(key)
535 iv = unhexlify(iv)
536 plaintext = unhexlify(plaintext)
537 ciphertext = unhexlify(ciphertext)
538
539 cipher = AES.new(key, AES.MODE_CBC, iv)
540 self.assertEqual(cipher.encrypt(plaintext), ciphertext)
541 cipher = AES.new(key, AES.MODE_CBC, iv)
542 self.assertEqual(cipher.decrypt(ciphertext), plaintext)
543
544
545 def get_tests(config={}):
546 tests = []
547 tests += list_test_cases(CbcTests)
548 if config.get('slow_tests'):
549 tests += list_test_cases(NistCbcVectors)
550 tests += list_test_cases(SP800TestVectors)
551 return tests
552
553
554 if __name__ == '__main__':
555 suite = lambda: unittest.TestSuite(get_tests())
556 unittest.main(defaultTest='suite')