Debian Codegraph @

lib/Crypto/SelfTest/Hash/test_CMAC.py

raw symbols SCIP
1 #
2 # SelfTest/Hash/CMAC.py: Self-test for the CMAC module
3 #
4 # ===================================================================
5 #
6 # Copyright (c) 2014, Legrandin <[email protected]>
7 # All rights reserved.
8 #
9 # Redistribution and use in source and binary forms, with or without
10 # modification, are permitted provided that the following conditions
11 # are met:
12 #
13 # 1. Redistributions of source code must retain the above copyright
14 # notice, this list of conditions and the following disclaimer.
15 # 2. Redistributions in binary form must reproduce the above copyright
16 # notice, this list of conditions and the following disclaimer in
17 # the documentation and/or other materials provided with the
18 # distribution.
19 #
20 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23 # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24 # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26 # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
28 # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
30 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31 # POSSIBILITY OF SUCH DAMAGE.
32 # ===================================================================
33
34 """Self-test suite for Crypto.Hash.CMAC"""
35
36 import json
37 import unittest
38 from binascii import unhexlify
39
40 from Crypto.Util.py3compat import tobytes
41
42 from Crypto.Hash import CMAC
43 from Crypto.Cipher import AES, DES3
44 from Crypto.Hash import SHAKE128
45
46 from Crypto.Util.strxor import strxor
47
48 from Crypto.SelfTest.st_common import list_test_cases
49 from Crypto.SelfTest.loader import load_test_vectors_wycheproof
50
51 # This is a list of (key, data, result, description, module) tuples.
52 test_data = [
53
54 ## Test vectors from RFC 4493 ##
55 ## The are also in NIST SP 800 38B D.2 ##
56 ( '2b7e151628aed2a6abf7158809cf4f3c',
57 '',
58 'bb1d6929e95937287fa37d129b756746',
59 'RFC 4493 #1',
60 AES
61 ),
62
63 ( '2b7e151628aed2a6abf7158809cf4f3c',
64 '6bc1bee22e409f96e93d7e117393172a',
65 '070a16b46b4d4144f79bdd9dd04a287c',
66 'RFC 4493 #2',
67 AES
68 ),
69
70 ( '2b7e151628aed2a6abf7158809cf4f3c',
71 '6bc1bee22e409f96e93d7e117393172a'+
72 'ae2d8a571e03ac9c9eb76fac45af8e51'+
73 '30c81c46a35ce411',
74 'dfa66747de9ae63030ca32611497c827',
75 'RFC 4493 #3',
76 AES
77 ),
78
79 ( '2b7e151628aed2a6abf7158809cf4f3c',
80 '6bc1bee22e409f96e93d7e117393172a'+
81 'ae2d8a571e03ac9c9eb76fac45af8e51'+
82 '30c81c46a35ce411e5fbc1191a0a52ef'+
83 'f69f2445df4f9b17ad2b417be66c3710',
84 '51f0bebf7e3b9d92fc49741779363cfe',
85 'RFC 4493 #4',
86 AES
87 ),
88
89 ## The rest of Appendix D of NIST SP 800 38B
90 ## was not totally correct.
91 ## Values in Examples 14, 15, 18, and 19 were wrong.
92 ## The updated test values are published in:
93 ## http://csrc.nist.gov/publications/nistpubs/800-38B/Updated_CMAC_Examples.pdf
94
95 ( '8e73b0f7da0e6452c810f32b809079e5'+
96 '62f8ead2522c6b7b',
97 '',
98 'd17ddf46adaacde531cac483de7a9367',
99 'NIST SP 800 38B D.2 Example 5',
100 AES
101 ),
102
103 ( '8e73b0f7da0e6452c810f32b809079e5'+
104 '62f8ead2522c6b7b',
105 '6bc1bee22e409f96e93d7e117393172a',
106 '9e99a7bf31e710900662f65e617c5184',
107 'NIST SP 800 38B D.2 Example 6',
108 AES
109 ),
110
111 ( '8e73b0f7da0e6452c810f32b809079e5'+
112 '62f8ead2522c6b7b',
113 '6bc1bee22e409f96e93d7e117393172a'+
114 'ae2d8a571e03ac9c9eb76fac45af8e51'+
115 '30c81c46a35ce411',
116 '8a1de5be2eb31aad089a82e6ee908b0e',
117 'NIST SP 800 38B D.2 Example 7',
118 AES
119 ),
120
121 ( '8e73b0f7da0e6452c810f32b809079e5'+
122 '62f8ead2522c6b7b',
123 '6bc1bee22e409f96e93d7e117393172a'+
124 'ae2d8a571e03ac9c9eb76fac45af8e51'+
125 '30c81c46a35ce411e5fbc1191a0a52ef'+
126 'f69f2445df4f9b17ad2b417be66c3710',
127 'a1d5df0eed790f794d77589659f39a11',
128 'NIST SP 800 38B D.2 Example 8',
129 AES
130 ),
131
132 ( '603deb1015ca71be2b73aef0857d7781'+
133 '1f352c073b6108d72d9810a30914dff4',
134 '',
135 '028962f61b7bf89efc6b551f4667d983',
136 'NIST SP 800 38B D.3 Example 9',
137 AES
138 ),
139
140 ( '603deb1015ca71be2b73aef0857d7781'+
141 '1f352c073b6108d72d9810a30914dff4',
142 '6bc1bee22e409f96e93d7e117393172a',
143 '28a7023f452e8f82bd4bf28d8c37c35c',
144 'NIST SP 800 38B D.3 Example 10',
145 AES
146 ),
147
148 ( '603deb1015ca71be2b73aef0857d7781'+
149 '1f352c073b6108d72d9810a30914dff4',
150 '6bc1bee22e409f96e93d7e117393172a'+
151 'ae2d8a571e03ac9c9eb76fac45af8e51'+
152 '30c81c46a35ce411',
153 'aaf3d8f1de5640c232f5b169b9c911e6',
154 'NIST SP 800 38B D.3 Example 11',
155 AES
156 ),
157
158 ( '603deb1015ca71be2b73aef0857d7781'+
159 '1f352c073b6108d72d9810a30914dff4',
160 '6bc1bee22e409f96e93d7e117393172a'+
161 'ae2d8a571e03ac9c9eb76fac45af8e51'+
162 '30c81c46a35ce411e5fbc1191a0a52ef'+
163 'f69f2445df4f9b17ad2b417be66c3710',
164 'e1992190549f6ed5696a2c056c315410',
165 'NIST SP 800 38B D.3 Example 12',
166 AES
167 ),
168
169 ( '8aa83bf8cbda1062'+
170 '0bc1bf19fbb6cd58'+
171 'bc313d4a371ca8b5',
172 '',
173 'b7a688e122ffaf95',
174 'NIST SP 800 38B D.4 Example 13',
175 DES3
176 ),
177
178 ( '8aa83bf8cbda1062'+
179 '0bc1bf19fbb6cd58'+
180 'bc313d4a371ca8b5',
181 '6bc1bee22e409f96',
182 '8e8f293136283797',
183 'NIST SP 800 38B D.4 Example 14',
184 DES3
185 ),
186
187 ( '8aa83bf8cbda1062'+
188 '0bc1bf19fbb6cd58'+
189 'bc313d4a371ca8b5',
190 '6bc1bee22e409f96'+
191 'e93d7e117393172a'+
192 'ae2d8a57',
193 '743ddbe0ce2dc2ed',
194 'NIST SP 800 38B D.4 Example 15',
195 DES3
196 ),
197
198 ( '8aa83bf8cbda1062'+
199 '0bc1bf19fbb6cd58'+
200 'bc313d4a371ca8b5',
201 '6bc1bee22e409f96'+
202 'e93d7e117393172a'+
203 'ae2d8a571e03ac9c'+
204 '9eb76fac45af8e51',
205 '33e6b1092400eae5',
206 'NIST SP 800 38B D.4 Example 16',
207 DES3
208 ),
209
210 ( '4cf15134a2850dd5'+
211 '8a3d10ba80570d38',
212 '',
213 'bd2ebf9a3ba00361',
214 'NIST SP 800 38B D.7 Example 17',
215 DES3
216 ),
217
218 ( '4cf15134a2850dd5'+
219 '8a3d10ba80570d38',
220 '6bc1bee22e409f96',
221 '4ff2ab813c53ce83',
222 'NIST SP 800 38B D.7 Example 18',
223 DES3
224 ),
225
226 ( '4cf15134a2850dd5'+
227 '8a3d10ba80570d38',
228 '6bc1bee22e409f96'+
229 'e93d7e117393172a'+
230 'ae2d8a57',
231 '62dd1b471902bd4e',
232 'NIST SP 800 38B D.7 Example 19',
233 DES3
234 ),
235
236 ( '4cf15134a2850dd5'+
237 '8a3d10ba80570d38',
238 '6bc1bee22e409f96'+
239 'e93d7e117393172a'+
240 'ae2d8a571e03ac9c'+
241 '9eb76fac45af8e51',
242 '31b1e431dabc4eb8',
243 'NIST SP 800 38B D.7 Example 20',
244 DES3
245 ),
246
247 ]
248
249
250 def get_tag_random(tag, length):
251 return SHAKE128.new(data=tobytes(tag)).read(length)
252
253
254 class TestCMAC(unittest.TestCase):
255
256 def test_internal_caching(self):
257 """Verify that internal caching is implemented correctly"""
258
259 data_to_mac = get_tag_random("data_to_mac", 128)
260 key = get_tag_random("key", 16)
261 ref_mac = CMAC.new(key, msg=data_to_mac, ciphermod=AES).digest()
262
263 # Break up in chunks of different length
264 # The result must always be the same
265 for chunk_length in 1, 2, 3, 7, 10, 13, 16, 40, 80, 128:
266
267 chunks = [data_to_mac[i:i+chunk_length] for i in
268 range(0, len(data_to_mac), chunk_length)]
269
270 mac = CMAC.new(key, ciphermod=AES)
271 for chunk in chunks:
272 mac.update(chunk)
273 self.assertEqual(ref_mac, mac.digest())
274
275 def test_update_after_digest(self):
276 msg = b"rrrrttt"
277 key = b"4" * 16
278
279 # Normally, update() cannot be done after digest()
280 h = CMAC.new(key, msg[:4], ciphermod=AES)
281 dig1 = h.digest()
282 self.assertRaises(TypeError, h.update, msg[4:])
283 dig2 = CMAC.new(key, msg, ciphermod=AES).digest()
284
285 # With the proper flag, it is allowed
286 h2 = CMAC.new(key, msg[:4], ciphermod=AES, update_after_digest=True)
287 self.assertEqual(h2.digest(), dig1)
288 # ... and the subsequent digest applies to the entire message
289 # up to that point
290 h2.update(msg[4:])
291 self.assertEqual(h2.digest(), dig2)
292
293
294 class ByteArrayTests(unittest.TestCase):
295
296 def runTest(self):
297
298 key = b"0" * 16
299 data = b"\x00\x01\x02"
300
301 # Data and key can be a bytearray (during initialization)
302 key_ba = bytearray(key)
303 data_ba = bytearray(data)
304
305 h1 = CMAC.new(key, data, ciphermod=AES)
306 h2 = CMAC.new(key_ba, data_ba, ciphermod=AES)
307 key_ba[:1] = b'\xFF'
308 data_ba[:1] = b'\xFF'
309 self.assertEqual(h1.digest(), h2.digest())
310
311 # Data can be a bytearray (during operation)
312 key_ba = bytearray(key)
313 data_ba = bytearray(data)
314
315 h1 = CMAC.new(key, ciphermod=AES)
316 h2 = CMAC.new(key, ciphermod=AES)
317 h1.update(data)
318 h2.update(data_ba)
319 data_ba[:1] = b'\xFF'
320 self.assertEqual(h1.digest(), h2.digest())
321
322
323 class MemoryViewTests(unittest.TestCase):
324
325 def runTest(self):
326
327 key = b"0" * 16
328 data = b"\x00\x01\x02"
329
330 def get_mv_ro(data):
331 return memoryview(data)
332
333 def get_mv_rw(data):
334 return memoryview(bytearray(data))
335
336 for get_mv in (get_mv_ro, get_mv_rw):
337
338 # Data and key can be a memoryview (during initialization)
339 key_mv = get_mv(key)
340 data_mv = get_mv(data)
341
342 h1 = CMAC.new(key, data, ciphermod=AES)
343 h2 = CMAC.new(key_mv, data_mv, ciphermod=AES)
344 if not data_mv.readonly:
345 key_mv[:1] = b'\xFF'
346 data_mv[:1] = b'\xFF'
347 self.assertEqual(h1.digest(), h2.digest())
348
349 # Data can be a memoryview (during operation)
350 data_mv = get_mv(data)
351
352 h1 = CMAC.new(key, ciphermod=AES)
353 h2 = CMAC.new(key, ciphermod=AES)
354 h1.update(data)
355 h2.update(data_mv)
356 if not data_mv.readonly:
357 data_mv[:1] = b'\xFF'
358 self.assertEqual(h1.digest(), h2.digest())
359
360
361 class TestVectorsWycheproof(unittest.TestCase):
362
363 def __init__(self, wycheproof_warnings):
364 unittest.TestCase.__init__(self)
365 self._wycheproof_warnings = wycheproof_warnings
366 self._id = "None"
367
368 def setUp(self):
369
370 def filter_tag(group):
371 return group['tagSize'] // 8
372
373 self.tv = load_test_vectors_wycheproof(("Hash", "wycheproof"),
374 "aes_cmac_test.json",
375 "Wycheproof CMAC",
376 group_tag={'tag_size': filter_tag})
377
378 def shortDescription(self):
379 return self._id
380
381 def warn(self, tv):
382 if tv.warning and self._wycheproof_warnings:
383 import warnings
384 warnings.warn("Wycheproof warning: %s (%s)" % (self._id, tv.comment))
385
386 def test_create_mac(self, tv):
387 self._id = "Wycheproof MAC creation Test #" + str(tv.id)
388
389 try:
390 tag = CMAC.new(tv.key, tv.msg, ciphermod=AES, mac_len=tv.tag_size).digest()
391 except ValueError as e:
392 if len(tv.key) not in (16, 24, 32) and "key length" in str(e):
393 return
394 raise e
395 if tv.valid:
396 self.assertEqual(tag, tv.tag)
397 self.warn(tv)
398
399 def test_verify_mac(self, tv):
400 self._id = "Wycheproof MAC verification Test #" + str(tv.id)
401
402 try:
403 mac = CMAC.new(tv.key, tv.msg, ciphermod=AES, mac_len=tv.tag_size)
404 except ValueError as e:
405 if len(tv.key) not in (16, 24, 32) and "key length" in str(e):
406 return
407 raise e
408 try:
409 mac.verify(tv.tag)
410 except ValueError:
411 assert not tv.valid
412 else:
413 assert tv.valid
414 self.warn(tv)
415
416 def runTest(self):
417
418 for tv in self.tv:
419 self.test_create_mac(tv)
420 self.test_verify_mac(tv)
421
422
423 def get_tests(config={}):
424 global test_data
425 import types
426 from .common import make_mac_tests
427
428 wycheproof_warnings = config.get('wycheproof_warnings')
429
430 # Add new() parameters to the back of each test vector
431 params_test_data = []
432 for row in test_data:
433 t = list(row)
434 t[4] = dict(ciphermod=t[4])
435 params_test_data.append(t)
436
437 tests = make_mac_tests(CMAC, "CMAC", params_test_data)
438 tests.append(ByteArrayTests())
439 tests.append(list_test_cases(TestCMAC))
440 tests.append(MemoryViewTests())
441 tests += [ TestVectorsWycheproof(wycheproof_warnings) ]
442 return tests
443
444
445 if __name__ == '__main__':
446 import unittest
447 suite = lambda: unittest.TestSuite(get_tests())
448 unittest.main(defaultTest='suite')