test_CMAC.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. #
  2. # SelfTest/Hash/CMAC.py: Self-test for the CMAC module
  3. #
  4. # ===================================================================
  5. #
  6. # Copyright (c) 2014, Legrandin <helderijs@gmail.com>
  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. """Self-test suite for Crypto.Hash.CMAC"""
  34. import json
  35. import unittest
  36. from binascii import unhexlify
  37. from tls.Crypto.Util.py3compat import tobytes, _memoryview
  38. from tls.Crypto.Hash import CMAC
  39. from tls.Crypto.Cipher import AES, DES3
  40. from tls.Crypto.Hash import SHAKE128
  41. from tls.Crypto.Util._file_system import pycryptodome_filename
  42. from tls.Crypto.Util.strxor import strxor
  43. from tls.Crypto.SelfTest.st_common import list_test_cases
  44. # This is a list of (key, data, result, description, module) tuples.
  45. test_data = [
  46. ## Test vectors from RFC 4493 ##
  47. ## The are also in NIST SP 800 38B D.2 ##
  48. ( '2b7e151628aed2a6abf7158809cf4f3c',
  49. '',
  50. 'bb1d6929e95937287fa37d129b756746',
  51. 'RFC 4493 #1',
  52. AES
  53. ),
  54. ( '2b7e151628aed2a6abf7158809cf4f3c',
  55. '6bc1bee22e409f96e93d7e117393172a',
  56. '070a16b46b4d4144f79bdd9dd04a287c',
  57. 'RFC 4493 #2',
  58. AES
  59. ),
  60. ( '2b7e151628aed2a6abf7158809cf4f3c',
  61. '6bc1bee22e409f96e93d7e117393172a'+
  62. 'ae2d8a571e03ac9c9eb76fac45af8e51'+
  63. '30c81c46a35ce411',
  64. 'dfa66747de9ae63030ca32611497c827',
  65. 'RFC 4493 #3',
  66. AES
  67. ),
  68. ( '2b7e151628aed2a6abf7158809cf4f3c',
  69. '6bc1bee22e409f96e93d7e117393172a'+
  70. 'ae2d8a571e03ac9c9eb76fac45af8e51'+
  71. '30c81c46a35ce411e5fbc1191a0a52ef'+
  72. 'f69f2445df4f9b17ad2b417be66c3710',
  73. '51f0bebf7e3b9d92fc49741779363cfe',
  74. 'RFC 4493 #4',
  75. AES
  76. ),
  77. ## The rest of Appendix D of NIST SP 800 38B
  78. ## was not totally correct.
  79. ## Values in Examples 14, 15, 18, and 19 were wrong.
  80. ## The updated test values are published in:
  81. ## http://csrc.nist.gov/publications/nistpubs/800-38B/Updated_CMAC_Examples.pdf
  82. ( '8e73b0f7da0e6452c810f32b809079e5'+
  83. '62f8ead2522c6b7b',
  84. '',
  85. 'd17ddf46adaacde531cac483de7a9367',
  86. 'NIST SP 800 38B D.2 Example 5',
  87. AES
  88. ),
  89. ( '8e73b0f7da0e6452c810f32b809079e5'+
  90. '62f8ead2522c6b7b',
  91. '6bc1bee22e409f96e93d7e117393172a',
  92. '9e99a7bf31e710900662f65e617c5184',
  93. 'NIST SP 800 38B D.2 Example 6',
  94. AES
  95. ),
  96. ( '8e73b0f7da0e6452c810f32b809079e5'+
  97. '62f8ead2522c6b7b',
  98. '6bc1bee22e409f96e93d7e117393172a'+
  99. 'ae2d8a571e03ac9c9eb76fac45af8e51'+
  100. '30c81c46a35ce411',
  101. '8a1de5be2eb31aad089a82e6ee908b0e',
  102. 'NIST SP 800 38B D.2 Example 7',
  103. AES
  104. ),
  105. ( '8e73b0f7da0e6452c810f32b809079e5'+
  106. '62f8ead2522c6b7b',
  107. '6bc1bee22e409f96e93d7e117393172a'+
  108. 'ae2d8a571e03ac9c9eb76fac45af8e51'+
  109. '30c81c46a35ce411e5fbc1191a0a52ef'+
  110. 'f69f2445df4f9b17ad2b417be66c3710',
  111. 'a1d5df0eed790f794d77589659f39a11',
  112. 'NIST SP 800 38B D.2 Example 8',
  113. AES
  114. ),
  115. ( '603deb1015ca71be2b73aef0857d7781'+
  116. '1f352c073b6108d72d9810a30914dff4',
  117. '',
  118. '028962f61b7bf89efc6b551f4667d983',
  119. 'NIST SP 800 38B D.3 Example 9',
  120. AES
  121. ),
  122. ( '603deb1015ca71be2b73aef0857d7781'+
  123. '1f352c073b6108d72d9810a30914dff4',
  124. '6bc1bee22e409f96e93d7e117393172a',
  125. '28a7023f452e8f82bd4bf28d8c37c35c',
  126. 'NIST SP 800 38B D.3 Example 10',
  127. AES
  128. ),
  129. ( '603deb1015ca71be2b73aef0857d7781'+
  130. '1f352c073b6108d72d9810a30914dff4',
  131. '6bc1bee22e409f96e93d7e117393172a'+
  132. 'ae2d8a571e03ac9c9eb76fac45af8e51'+
  133. '30c81c46a35ce411',
  134. 'aaf3d8f1de5640c232f5b169b9c911e6',
  135. 'NIST SP 800 38B D.3 Example 11',
  136. AES
  137. ),
  138. ( '603deb1015ca71be2b73aef0857d7781'+
  139. '1f352c073b6108d72d9810a30914dff4',
  140. '6bc1bee22e409f96e93d7e117393172a'+
  141. 'ae2d8a571e03ac9c9eb76fac45af8e51'+
  142. '30c81c46a35ce411e5fbc1191a0a52ef'+
  143. 'f69f2445df4f9b17ad2b417be66c3710',
  144. 'e1992190549f6ed5696a2c056c315410',
  145. 'NIST SP 800 38B D.3 Example 12',
  146. AES
  147. ),
  148. ( '8aa83bf8cbda1062'+
  149. '0bc1bf19fbb6cd58'+
  150. 'bc313d4a371ca8b5',
  151. '',
  152. 'b7a688e122ffaf95',
  153. 'NIST SP 800 38B D.4 Example 13',
  154. DES3
  155. ),
  156. ( '8aa83bf8cbda1062'+
  157. '0bc1bf19fbb6cd58'+
  158. 'bc313d4a371ca8b5',
  159. '6bc1bee22e409f96',
  160. '8e8f293136283797',
  161. 'NIST SP 800 38B D.4 Example 14',
  162. DES3
  163. ),
  164. ( '8aa83bf8cbda1062'+
  165. '0bc1bf19fbb6cd58'+
  166. 'bc313d4a371ca8b5',
  167. '6bc1bee22e409f96'+
  168. 'e93d7e117393172a'+
  169. 'ae2d8a57',
  170. '743ddbe0ce2dc2ed',
  171. 'NIST SP 800 38B D.4 Example 15',
  172. DES3
  173. ),
  174. ( '8aa83bf8cbda1062'+
  175. '0bc1bf19fbb6cd58'+
  176. 'bc313d4a371ca8b5',
  177. '6bc1bee22e409f96'+
  178. 'e93d7e117393172a'+
  179. 'ae2d8a571e03ac9c'+
  180. '9eb76fac45af8e51',
  181. '33e6b1092400eae5',
  182. 'NIST SP 800 38B D.4 Example 16',
  183. DES3
  184. ),
  185. ( '4cf15134a2850dd5'+
  186. '8a3d10ba80570d38',
  187. '',
  188. 'bd2ebf9a3ba00361',
  189. 'NIST SP 800 38B D.7 Example 17',
  190. DES3
  191. ),
  192. ( '4cf15134a2850dd5'+
  193. '8a3d10ba80570d38',
  194. '6bc1bee22e409f96',
  195. '4ff2ab813c53ce83',
  196. 'NIST SP 800 38B D.7 Example 18',
  197. DES3
  198. ),
  199. ( '4cf15134a2850dd5'+
  200. '8a3d10ba80570d38',
  201. '6bc1bee22e409f96'+
  202. 'e93d7e117393172a'+
  203. 'ae2d8a57',
  204. '62dd1b471902bd4e',
  205. 'NIST SP 800 38B D.7 Example 19',
  206. DES3
  207. ),
  208. ( '4cf15134a2850dd5'+
  209. '8a3d10ba80570d38',
  210. '6bc1bee22e409f96'+
  211. 'e93d7e117393172a'+
  212. 'ae2d8a571e03ac9c'+
  213. '9eb76fac45af8e51',
  214. '31b1e431dabc4eb8',
  215. 'NIST SP 800 38B D.7 Example 20',
  216. DES3
  217. ),
  218. ]
  219. def get_tag_random(tag, length):
  220. return SHAKE128.new(data=tobytes(tag)).read(length)
  221. class TestCMAC(unittest.TestCase):
  222. def test_internal_caching(self):
  223. """Verify that internal caching is implemented correctly"""
  224. data_to_mac = get_tag_random("data_to_mac", 128)
  225. key = get_tag_random("key", 16)
  226. ref_mac = CMAC.new(key, msg=data_to_mac, ciphermod=AES).digest()
  227. # Break up in chunks of different length
  228. # The result must always be the same
  229. for chunk_length in 1, 2, 3, 7, 10, 13, 16, 40, 80, 128:
  230. chunks = [data_to_mac[i:i+chunk_length] for i in
  231. range(0, len(data_to_mac), chunk_length)]
  232. mac = CMAC.new(key, ciphermod=AES)
  233. for chunk in chunks:
  234. mac.update(chunk)
  235. self.assertEqual(ref_mac, mac.digest())
  236. def test_update_after_digest(self):
  237. msg = b"rrrrttt"
  238. key = b"4" * 16
  239. # Normally, update() cannot be done after digest()
  240. h = CMAC.new(key, msg[:4], ciphermod=AES)
  241. dig1 = h.digest()
  242. self.assertRaises(TypeError, h.update, msg[4:])
  243. dig2 = CMAC.new(key, msg, ciphermod=AES).digest()
  244. # With the proper flag, it is allowed
  245. h2 = CMAC.new(key, msg[:4], ciphermod=AES, update_after_digest=True)
  246. self.assertEquals(h2.digest(), dig1)
  247. # ... and the subsequent digest applies to the entire message
  248. # up to that point
  249. h2.update(msg[4:])
  250. self.assertEquals(h2.digest(), dig2)
  251. class ByteArrayTests(unittest.TestCase):
  252. def runTest(self):
  253. key = b"0" * 16
  254. data = b"\x00\x01\x02"
  255. # Data and key can be a bytearray (during initialization)
  256. key_ba = bytearray(key)
  257. data_ba = bytearray(data)
  258. h1 = CMAC.new(key, data, ciphermod=AES)
  259. h2 = CMAC.new(key_ba, data_ba, ciphermod=AES)
  260. key_ba[:1] = b'\xFF'
  261. data_ba[:1] = b'\xFF'
  262. self.assertEqual(h1.digest(), h2.digest())
  263. # Data can be a bytearray (during operation)
  264. key_ba = bytearray(key)
  265. data_ba = bytearray(data)
  266. h1 = CMAC.new(key, ciphermod=AES)
  267. h2 = CMAC.new(key, ciphermod=AES)
  268. h1.update(data)
  269. h2.update(data_ba)
  270. data_ba[:1] = b'\xFF'
  271. self.assertEqual(h1.digest(), h2.digest())
  272. class MemoryViewTests(unittest.TestCase):
  273. def runTest(self):
  274. key = b"0" * 16
  275. data = b"\x00\x01\x02"
  276. def get_mv_ro(data):
  277. return memoryview(data)
  278. def get_mv_rw(data):
  279. return memoryview(bytearray(data))
  280. for get_mv in (get_mv_ro, get_mv_rw):
  281. # Data and key can be a memoryview (during initialization)
  282. key_mv = get_mv(key)
  283. data_mv = get_mv(data)
  284. h1 = CMAC.new(key, data, ciphermod=AES)
  285. h2 = CMAC.new(key_mv, data_mv, ciphermod=AES)
  286. if not data_mv.readonly:
  287. key_mv[:1] = b'\xFF'
  288. data_mv[:1] = b'\xFF'
  289. self.assertEqual(h1.digest(), h2.digest())
  290. # Data can be a memoryview (during operation)
  291. data_mv = get_mv(data)
  292. h1 = CMAC.new(key, ciphermod=AES)
  293. h2 = CMAC.new(key, ciphermod=AES)
  294. h1.update(data)
  295. h2.update(data_mv)
  296. if not data_mv.readonly:
  297. data_mv[:1] = b'\xFF'
  298. self.assertEqual(h1.digest(), h2.digest())
  299. class TestVectorsWycheproof(unittest.TestCase):
  300. def __init__(self, wycheproof_warnings):
  301. unittest.TestCase.__init__(self)
  302. self._wycheproof_warnings = wycheproof_warnings
  303. self._id = "None"
  304. def setUp(self):
  305. comps = "Crypto.SelfTest.Hash.test_vectors.wycheproof".split(".")
  306. with open(pycryptodome_filename(comps, "aes_cmac_test.json"), "rt") as file_in:
  307. tv_tree = json.load(file_in)
  308. class TestVector(object):
  309. pass
  310. self.tv = []
  311. for group in tv_tree['testGroups']:
  312. tag_size = group['tagSize'] // 8
  313. for test in group['tests']:
  314. tv = TestVector()
  315. tv.tag_size = tag_size
  316. tv.id = test['tcId']
  317. tv.comment = test['comment']
  318. for attr in 'key', 'msg', 'tag':
  319. setattr(tv, attr, unhexlify(test[attr]))
  320. tv.valid = test['result'] != "invalid"
  321. tv.warning = test['result'] == "acceptable"
  322. self.tv.append(tv)
  323. def shortDescription(self):
  324. return self._id
  325. def warn(self, tv):
  326. if tv.warning and self._wycheproof_warnings:
  327. import warnings
  328. warnings.warn("Wycheproof warning: %s (%s)" % (self._id, tv.comment))
  329. def test_create_mac(self, tv):
  330. self._id = "Wycheproof MAC creation Test #" + str(tv.id)
  331. try:
  332. tag = CMAC.new(tv.key, tv.msg, ciphermod=AES, mac_len=tv.tag_size).digest()
  333. except ValueError as e:
  334. if len(tv.key) not in (16, 24, 32) and "key length" in str(e):
  335. return
  336. raise e
  337. if tv.valid:
  338. self.assertEqual(tag, tv.tag)
  339. self.warn(tv)
  340. def test_verify_mac(self, tv):
  341. self._id = "Wycheproof MAC verification Test #" + str(tv.id)
  342. try:
  343. mac = CMAC.new(tv.key, tv.msg, ciphermod=AES, mac_len=tv.tag_size)
  344. except ValueError as e:
  345. if len(tv.key) not in (16, 24, 32) and "key length" in str(e):
  346. return
  347. raise e
  348. try:
  349. mac.verify(tv.tag)
  350. except ValueError:
  351. assert not tv.valid
  352. else:
  353. assert tv.valid
  354. self.warn(tv)
  355. def runTest(self):
  356. for tv in self.tv:
  357. self.test_create_mac(tv)
  358. self.test_verify_mac(tv)
  359. def get_tests(config={}):
  360. global test_data
  361. import types
  362. from .common import make_mac_tests
  363. wycheproof_warnings = config.get('wycheproof_warnings')
  364. # Add new() parameters to the back of each test vector
  365. params_test_data = []
  366. for row in test_data:
  367. t = list(row)
  368. t[4] = dict(ciphermod=t[4])
  369. params_test_data.append(t)
  370. tests = make_mac_tests(CMAC, "CMAC", params_test_data)
  371. tests.append(ByteArrayTests())
  372. tests.append(list_test_cases(TestCMAC))
  373. import sys
  374. if sys.version[:3] != "2.6":
  375. tests.append(MemoryViewTests())
  376. tests += [ TestVectorsWycheproof(wycheproof_warnings) ]
  377. return tests
  378. if __name__ == '__main__':
  379. import unittest
  380. suite = lambda: unittest.TestSuite(get_tests())
  381. unittest.main(defaultTest='suite')