test_CCM.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930
  1. # ===================================================================
  2. #
  3. # Copyright (c) 2015, Legrandin <helderijs@gmail.com>
  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. import unittest
  31. from binascii import unhexlify
  32. from Crypto.SelfTest.st_common import list_test_cases
  33. from Crypto.SelfTest.loader import load_test_vectors_wycheproof
  34. from Crypto.Util.py3compat import tobytes, bchr
  35. from Crypto.Cipher import AES
  36. from Crypto.Hash import SHAKE128
  37. from Crypto.Util.strxor import strxor
  38. def get_tag_random(tag, length):
  39. return SHAKE128.new(data=tobytes(tag)).read(length)
  40. class CcmTests(unittest.TestCase):
  41. key_128 = get_tag_random("key_128", 16)
  42. nonce_96 = get_tag_random("nonce_128", 12)
  43. data_128 = get_tag_random("data_128", 16)
  44. def test_loopback_128(self):
  45. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  46. pt = get_tag_random("plaintext", 16 * 100)
  47. ct = cipher.encrypt(pt)
  48. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  49. pt2 = cipher.decrypt(ct)
  50. self.assertEqual(pt, pt2)
  51. def test_nonce(self):
  52. # If not passed, the nonce is created randomly
  53. cipher = AES.new(self.key_128, AES.MODE_CCM)
  54. nonce1 = cipher.nonce
  55. cipher = AES.new(self.key_128, AES.MODE_CCM)
  56. nonce2 = cipher.nonce
  57. self.assertEqual(len(nonce1), 11)
  58. self.assertNotEqual(nonce1, nonce2)
  59. cipher = AES.new(self.key_128, AES.MODE_CCM, self.nonce_96)
  60. ct = cipher.encrypt(self.data_128)
  61. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  62. self.assertEquals(ct, cipher.encrypt(self.data_128))
  63. def test_nonce_must_be_bytes(self):
  64. self.assertRaises(TypeError, AES.new, self.key_128, AES.MODE_CCM,
  65. nonce=u'test12345678')
  66. def test_nonce_length(self):
  67. self.assertRaises(ValueError, AES.new, self.key_128, AES.MODE_CCM,
  68. nonce=b"")
  69. self.assertRaises(ValueError, AES.new, self.key_128, AES.MODE_CCM,
  70. nonce=bchr(1) * 6)
  71. self.assertRaises(ValueError, AES.new, self.key_128, AES.MODE_CCM,
  72. nonce=bchr(1) * 14)
  73. for x in range(7, 13 + 1):
  74. AES.new(self.key_128, AES.MODE_CCM, nonce=bchr(1) * x)
  75. def test_block_size(self):
  76. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  77. self.assertEqual(cipher.block_size, AES.block_size)
  78. def test_nonce_attribute(self):
  79. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  80. self.assertEqual(cipher.nonce, self.nonce_96)
  81. # By default, a 11 bytes long nonce is randomly generated
  82. nonce1 = AES.new(self.key_128, AES.MODE_CCM).nonce
  83. nonce2 = AES.new(self.key_128, AES.MODE_CCM).nonce
  84. self.assertEqual(len(nonce1), 11)
  85. self.assertNotEqual(nonce1, nonce2)
  86. def test_unknown_parameters(self):
  87. self.assertRaises(TypeError, AES.new, self.key_128, AES.MODE_CCM,
  88. self.nonce_96, 7)
  89. self.assertRaises(TypeError, AES.new, self.key_128, AES.MODE_CCM,
  90. nonce=self.nonce_96, unknown=7)
  91. # But some are only known by the base cipher
  92. # (e.g. use_aesni consumed by the AES module)
  93. AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96,
  94. use_aesni=False)
  95. def test_null_encryption_decryption(self):
  96. for func in "encrypt", "decrypt":
  97. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  98. result = getattr(cipher, func)(b"")
  99. self.assertEqual(result, b"")
  100. def test_either_encrypt_or_decrypt(self):
  101. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  102. cipher.encrypt(b"")
  103. self.assertRaises(TypeError, cipher.decrypt, b"")
  104. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  105. cipher.decrypt(b"")
  106. self.assertRaises(TypeError, cipher.encrypt, b"")
  107. def test_data_must_be_bytes(self):
  108. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  109. self.assertRaises(TypeError, cipher.encrypt, u'test1234567890-*')
  110. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  111. self.assertRaises(TypeError, cipher.decrypt, u'test1234567890-*')
  112. def test_mac_len(self):
  113. # Invalid MAC length
  114. for mac_len in range(3, 17 + 1, 2):
  115. self.assertRaises(ValueError, AES.new, self.key_128, AES.MODE_CCM,
  116. nonce=self.nonce_96, mac_len=mac_len)
  117. # Valid MAC length
  118. for mac_len in range(4, 16 + 1, 2):
  119. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96,
  120. mac_len=mac_len)
  121. _, mac = cipher.encrypt_and_digest(self.data_128)
  122. self.assertEqual(len(mac), mac_len)
  123. # Default MAC length
  124. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  125. _, mac = cipher.encrypt_and_digest(self.data_128)
  126. self.assertEqual(len(mac), 16)
  127. def test_invalid_mac(self):
  128. from Crypto.Util.strxor import strxor_c
  129. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  130. ct, mac = cipher.encrypt_and_digest(self.data_128)
  131. invalid_mac = strxor_c(mac, 0x01)
  132. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  133. self.assertRaises(ValueError, cipher.decrypt_and_verify, ct,
  134. invalid_mac)
  135. def test_hex_mac(self):
  136. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  137. mac_hex = cipher.hexdigest()
  138. self.assertEqual(cipher.digest(), unhexlify(mac_hex))
  139. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  140. cipher.hexverify(mac_hex)
  141. def test_longer_assoc_data_than_declared(self):
  142. # More than zero
  143. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96,
  144. assoc_len=0)
  145. self.assertRaises(ValueError, cipher.update, b"1")
  146. # Too large
  147. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96,
  148. assoc_len=15)
  149. self.assertRaises(ValueError, cipher.update, self.data_128)
  150. def test_shorter_assoc_data_than_expected(self):
  151. # With plaintext
  152. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96,
  153. assoc_len=17)
  154. cipher.update(self.data_128)
  155. self.assertRaises(ValueError, cipher.encrypt, self.data_128)
  156. # With empty plaintext
  157. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96,
  158. assoc_len=17)
  159. cipher.update(self.data_128)
  160. self.assertRaises(ValueError, cipher.digest)
  161. # With ciphertext
  162. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96,
  163. assoc_len=17)
  164. cipher.update(self.data_128)
  165. self.assertRaises(ValueError, cipher.decrypt, self.data_128)
  166. # With empty ciphertext
  167. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  168. cipher.update(self.data_128)
  169. mac = cipher.digest()
  170. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96,
  171. assoc_len=17)
  172. cipher.update(self.data_128)
  173. self.assertRaises(ValueError, cipher.verify, mac)
  174. def test_shorter_and_longer_plaintext_than_declared(self):
  175. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96,
  176. msg_len=17)
  177. cipher.encrypt(self.data_128)
  178. self.assertRaises(ValueError, cipher.digest)
  179. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96,
  180. msg_len=15)
  181. self.assertRaises(ValueError, cipher.encrypt, self.data_128)
  182. def test_shorter_ciphertext_than_declared(self):
  183. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  184. ct, mac = cipher.encrypt_and_digest(self.data_128)
  185. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96,
  186. msg_len=17)
  187. cipher.decrypt(ct)
  188. self.assertRaises(ValueError, cipher.verify, mac)
  189. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96,
  190. msg_len=15)
  191. self.assertRaises(ValueError, cipher.decrypt, ct)
  192. def test_message_chunks(self):
  193. # Validate that both associated data and plaintext/ciphertext
  194. # can be broken up in chunks of arbitrary length
  195. auth_data = get_tag_random("authenticated data", 127)
  196. plaintext = get_tag_random("plaintext", 127)
  197. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  198. cipher.update(auth_data)
  199. ciphertext, ref_mac = cipher.encrypt_and_digest(plaintext)
  200. def break_up(data, chunk_length):
  201. return [data[i:i+chunk_length] for i in range(0, len(data),
  202. chunk_length)]
  203. # Encryption
  204. for chunk_length in 1, 2, 3, 7, 10, 13, 16, 40, 80, 128:
  205. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96,
  206. msg_len=127, assoc_len=127)
  207. for chunk in break_up(auth_data, chunk_length):
  208. cipher.update(chunk)
  209. pt2 = b""
  210. for chunk in break_up(ciphertext, chunk_length):
  211. pt2 += cipher.decrypt(chunk)
  212. self.assertEqual(plaintext, pt2)
  213. cipher.verify(ref_mac)
  214. # Decryption
  215. for chunk_length in 1, 2, 3, 7, 10, 13, 16, 40, 80, 128:
  216. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96,
  217. msg_len=127, assoc_len=127)
  218. for chunk in break_up(auth_data, chunk_length):
  219. cipher.update(chunk)
  220. ct2 = b""
  221. for chunk in break_up(plaintext, chunk_length):
  222. ct2 += cipher.encrypt(chunk)
  223. self.assertEqual(ciphertext, ct2)
  224. self.assertEquals(cipher.digest(), ref_mac)
  225. def test_bytearray(self):
  226. # Encrypt
  227. key_ba = bytearray(self.key_128)
  228. nonce_ba = bytearray(self.nonce_96)
  229. header_ba = bytearray(self.data_128)
  230. data_ba = bytearray(self.data_128)
  231. cipher1 = AES.new(self.key_128,
  232. AES.MODE_CCM,
  233. nonce=self.nonce_96)
  234. cipher1.update(self.data_128)
  235. ct = cipher1.encrypt(self.data_128)
  236. tag = cipher1.digest()
  237. cipher2 = AES.new(key_ba,
  238. AES.MODE_CCM,
  239. nonce=nonce_ba)
  240. key_ba[:3] = b"\xFF\xFF\xFF"
  241. nonce_ba[:3] = b"\xFF\xFF\xFF"
  242. cipher2.update(header_ba)
  243. header_ba[:3] = b"\xFF\xFF\xFF"
  244. ct_test = cipher2.encrypt(data_ba)
  245. data_ba[:3] = b"\xFF\xFF\xFF"
  246. tag_test = cipher2.digest()
  247. self.assertEqual(ct, ct_test)
  248. self.assertEqual(tag, tag_test)
  249. self.assertEqual(cipher1.nonce, cipher2.nonce)
  250. # Decrypt
  251. key_ba = bytearray(self.key_128)
  252. nonce_ba = bytearray(self.nonce_96)
  253. header_ba = bytearray(self.data_128)
  254. del data_ba
  255. cipher4 = AES.new(key_ba,
  256. AES.MODE_CCM,
  257. nonce=nonce_ba)
  258. key_ba[:3] = b"\xFF\xFF\xFF"
  259. nonce_ba[:3] = b"\xFF\xFF\xFF"
  260. cipher4.update(header_ba)
  261. header_ba[:3] = b"\xFF\xFF\xFF"
  262. pt_test = cipher4.decrypt_and_verify(bytearray(ct_test), bytearray(tag_test))
  263. self.assertEqual(self.data_128, pt_test)
  264. def test_memoryview(self):
  265. # Encrypt
  266. key_mv = memoryview(bytearray(self.key_128))
  267. nonce_mv = memoryview(bytearray(self.nonce_96))
  268. header_mv = memoryview(bytearray(self.data_128))
  269. data_mv = memoryview(bytearray(self.data_128))
  270. cipher1 = AES.new(self.key_128,
  271. AES.MODE_CCM,
  272. nonce=self.nonce_96)
  273. cipher1.update(self.data_128)
  274. ct = cipher1.encrypt(self.data_128)
  275. tag = cipher1.digest()
  276. cipher2 = AES.new(key_mv,
  277. AES.MODE_CCM,
  278. nonce=nonce_mv)
  279. key_mv[:3] = b"\xFF\xFF\xFF"
  280. nonce_mv[:3] = b"\xFF\xFF\xFF"
  281. cipher2.update(header_mv)
  282. header_mv[:3] = b"\xFF\xFF\xFF"
  283. ct_test = cipher2.encrypt(data_mv)
  284. data_mv[:3] = b"\xFF\xFF\xFF"
  285. tag_test = cipher2.digest()
  286. self.assertEqual(ct, ct_test)
  287. self.assertEqual(tag, tag_test)
  288. self.assertEqual(cipher1.nonce, cipher2.nonce)
  289. # Decrypt
  290. key_mv = memoryview(bytearray(self.key_128))
  291. nonce_mv = memoryview(bytearray(self.nonce_96))
  292. header_mv = memoryview(bytearray(self.data_128))
  293. del data_mv
  294. cipher4 = AES.new(key_mv,
  295. AES.MODE_CCM,
  296. nonce=nonce_mv)
  297. key_mv[:3] = b"\xFF\xFF\xFF"
  298. nonce_mv[:3] = b"\xFF\xFF\xFF"
  299. cipher4.update(header_mv)
  300. header_mv[:3] = b"\xFF\xFF\xFF"
  301. pt_test = cipher4.decrypt_and_verify(memoryview(ct_test), memoryview(tag_test))
  302. self.assertEqual(self.data_128, pt_test)
  303. def test_output_param(self):
  304. pt = b'5' * 16
  305. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  306. ct = cipher.encrypt(pt)
  307. tag = cipher.digest()
  308. output = bytearray(16)
  309. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  310. res = cipher.encrypt(pt, output=output)
  311. self.assertEqual(ct, output)
  312. self.assertEqual(res, None)
  313. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  314. res = cipher.decrypt(ct, output=output)
  315. self.assertEqual(pt, output)
  316. self.assertEqual(res, None)
  317. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  318. res, tag_out = cipher.encrypt_and_digest(pt, output=output)
  319. self.assertEqual(ct, output)
  320. self.assertEqual(res, None)
  321. self.assertEqual(tag, tag_out)
  322. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  323. res = cipher.decrypt_and_verify(ct, tag, output=output)
  324. self.assertEqual(pt, output)
  325. self.assertEqual(res, None)
  326. def test_output_param_memoryview(self):
  327. pt = b'5' * 16
  328. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  329. ct = cipher.encrypt(pt)
  330. output = memoryview(bytearray(16))
  331. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  332. cipher.encrypt(pt, output=output)
  333. self.assertEqual(ct, output)
  334. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  335. cipher.decrypt(ct, output=output)
  336. self.assertEqual(pt, output)
  337. def test_output_param_neg(self):
  338. pt = b'5' * 16
  339. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  340. ct = cipher.encrypt(pt)
  341. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  342. self.assertRaises(TypeError, cipher.encrypt, pt, output=b'0'*16)
  343. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  344. self.assertRaises(TypeError, cipher.decrypt, ct, output=b'0'*16)
  345. shorter_output = bytearray(15)
  346. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  347. self.assertRaises(ValueError, cipher.encrypt, pt, output=shorter_output)
  348. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  349. self.assertRaises(ValueError, cipher.decrypt, ct, output=shorter_output)
  350. class CcmFSMTests(unittest.TestCase):
  351. key_128 = get_tag_random("key_128", 16)
  352. nonce_96 = get_tag_random("nonce_128", 12)
  353. data_128 = get_tag_random("data_128", 16)
  354. def test_valid_init_encrypt_decrypt_digest_verify(self):
  355. # No authenticated data, fixed plaintext
  356. for assoc_len in (None, 0):
  357. for msg_len in (None, len(self.data_128)):
  358. # Verify path INIT->ENCRYPT->DIGEST
  359. cipher = AES.new(self.key_128, AES.MODE_CCM,
  360. nonce=self.nonce_96,
  361. assoc_len=assoc_len,
  362. msg_len=msg_len)
  363. ct = cipher.encrypt(self.data_128)
  364. mac = cipher.digest()
  365. # Verify path INIT->DECRYPT->VERIFY
  366. cipher = AES.new(self.key_128, AES.MODE_CCM,
  367. nonce=self.nonce_96,
  368. assoc_len=assoc_len,
  369. msg_len=msg_len)
  370. cipher.decrypt(ct)
  371. cipher.verify(mac)
  372. def test_valid_init_update_digest_verify(self):
  373. # No plaintext, fixed authenticated data
  374. for assoc_len in (None, len(self.data_128)):
  375. for msg_len in (None, 0):
  376. # Verify path INIT->UPDATE->DIGEST
  377. cipher = AES.new(self.key_128, AES.MODE_CCM,
  378. nonce=self.nonce_96,
  379. assoc_len=assoc_len,
  380. msg_len=msg_len)
  381. cipher.update(self.data_128)
  382. mac = cipher.digest()
  383. # Verify path INIT->UPDATE->VERIFY
  384. cipher = AES.new(self.key_128, AES.MODE_CCM,
  385. nonce=self.nonce_96,
  386. assoc_len=assoc_len,
  387. msg_len=msg_len)
  388. cipher.update(self.data_128)
  389. cipher.verify(mac)
  390. def test_valid_full_path(self):
  391. # Fixed authenticated data, fixed plaintext
  392. for assoc_len in (None, len(self.data_128)):
  393. for msg_len in (None, len(self.data_128)):
  394. # Verify path INIT->UPDATE->ENCRYPT->DIGEST
  395. cipher = AES.new(self.key_128, AES.MODE_CCM,
  396. nonce=self.nonce_96,
  397. assoc_len=assoc_len,
  398. msg_len=msg_len)
  399. cipher.update(self.data_128)
  400. ct = cipher.encrypt(self.data_128)
  401. mac = cipher.digest()
  402. # Verify path INIT->UPDATE->DECRYPT->VERIFY
  403. cipher = AES.new(self.key_128, AES.MODE_CCM,
  404. nonce=self.nonce_96,
  405. assoc_len=assoc_len,
  406. msg_len=msg_len)
  407. cipher.update(self.data_128)
  408. cipher.decrypt(ct)
  409. cipher.verify(mac)
  410. def test_valid_init_digest(self):
  411. # Verify path INIT->DIGEST
  412. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  413. cipher.digest()
  414. def test_valid_init_verify(self):
  415. # Verify path INIT->VERIFY
  416. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  417. mac = cipher.digest()
  418. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  419. cipher.verify(mac)
  420. def test_valid_multiple_encrypt_or_decrypt(self):
  421. # Only possible if msg_len is declared in advance
  422. for method_name in "encrypt", "decrypt":
  423. for auth_data in (None, b"333", self.data_128,
  424. self.data_128 + b"3"):
  425. if auth_data is None:
  426. assoc_len = None
  427. else:
  428. assoc_len = len(auth_data)
  429. cipher = AES.new(self.key_128, AES.MODE_CCM,
  430. nonce=self.nonce_96,
  431. msg_len=64,
  432. assoc_len=assoc_len)
  433. if auth_data is not None:
  434. cipher.update(auth_data)
  435. method = getattr(cipher, method_name)
  436. method(self.data_128)
  437. method(self.data_128)
  438. method(self.data_128)
  439. method(self.data_128)
  440. def test_valid_multiple_digest_or_verify(self):
  441. # Multiple calls to digest
  442. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  443. cipher.update(self.data_128)
  444. first_mac = cipher.digest()
  445. for x in range(4):
  446. self.assertEqual(first_mac, cipher.digest())
  447. # Multiple calls to verify
  448. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  449. cipher.update(self.data_128)
  450. for x in range(5):
  451. cipher.verify(first_mac)
  452. def test_valid_encrypt_and_digest_decrypt_and_verify(self):
  453. # encrypt_and_digest
  454. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  455. cipher.update(self.data_128)
  456. ct, mac = cipher.encrypt_and_digest(self.data_128)
  457. # decrypt_and_verify
  458. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  459. cipher.update(self.data_128)
  460. pt = cipher.decrypt_and_verify(ct, mac)
  461. self.assertEqual(self.data_128, pt)
  462. def test_invalid_multiple_encrypt_decrypt_without_msg_len(self):
  463. # Once per method, with or without assoc. data
  464. for method_name in "encrypt", "decrypt":
  465. for assoc_data_present in (True, False):
  466. cipher = AES.new(self.key_128, AES.MODE_CCM,
  467. nonce=self.nonce_96)
  468. if assoc_data_present:
  469. cipher.update(self.data_128)
  470. method = getattr(cipher, method_name)
  471. method(self.data_128)
  472. self.assertRaises(TypeError, method, self.data_128)
  473. def test_invalid_mixing_encrypt_decrypt(self):
  474. # Once per method, with or without assoc. data
  475. for method1_name, method2_name in (("encrypt", "decrypt"),
  476. ("decrypt", "encrypt")):
  477. for assoc_data_present in (True, False):
  478. cipher = AES.new(self.key_128, AES.MODE_CCM,
  479. nonce=self.nonce_96,
  480. msg_len=32)
  481. if assoc_data_present:
  482. cipher.update(self.data_128)
  483. getattr(cipher, method1_name)(self.data_128)
  484. self.assertRaises(TypeError, getattr(cipher, method2_name),
  485. self.data_128)
  486. def test_invalid_encrypt_or_update_after_digest(self):
  487. for method_name in "encrypt", "update":
  488. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  489. cipher.encrypt(self.data_128)
  490. cipher.digest()
  491. self.assertRaises(TypeError, getattr(cipher, method_name),
  492. self.data_128)
  493. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  494. cipher.encrypt_and_digest(self.data_128)
  495. def test_invalid_decrypt_or_update_after_verify(self):
  496. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  497. ct = cipher.encrypt(self.data_128)
  498. mac = cipher.digest()
  499. for method_name in "decrypt", "update":
  500. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  501. cipher.decrypt(ct)
  502. cipher.verify(mac)
  503. self.assertRaises(TypeError, getattr(cipher, method_name),
  504. self.data_128)
  505. cipher = AES.new(self.key_128, AES.MODE_CCM, nonce=self.nonce_96)
  506. cipher.decrypt_and_verify(ct, mac)
  507. self.assertRaises(TypeError, getattr(cipher, method_name),
  508. self.data_128)
  509. class TestVectors(unittest.TestCase):
  510. """Class exercising the CCM test vectors found in Appendix C
  511. of NIST SP 800-38C and in RFC 3610"""
  512. # List of test vectors, each made up of:
  513. # - authenticated data
  514. # - plaintext
  515. # - ciphertext
  516. # - MAC
  517. # - AES key
  518. # - nonce
  519. test_vectors_hex = [
  520. # NIST SP 800 38C
  521. ( '0001020304050607',
  522. '20212223',
  523. '7162015b',
  524. '4dac255d',
  525. '404142434445464748494a4b4c4d4e4f',
  526. '10111213141516'),
  527. ( '000102030405060708090a0b0c0d0e0f',
  528. '202122232425262728292a2b2c2d2e2f',
  529. 'd2a1f0e051ea5f62081a7792073d593d',
  530. '1fc64fbfaccd',
  531. '404142434445464748494a4b4c4d4e4f',
  532. '1011121314151617'),
  533. ( '000102030405060708090a0b0c0d0e0f10111213',
  534. '202122232425262728292a2b2c2d2e2f3031323334353637',
  535. 'e3b201a9f5b71a7a9b1ceaeccd97e70b6176aad9a4428aa5',
  536. '484392fbc1b09951',
  537. '404142434445464748494a4b4c4d4e4f',
  538. '101112131415161718191a1b'),
  539. ( (''.join(["%02X" % (x*16+y) for x in range(0,16) for y in range(0,16)]))*256,
  540. '202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f',
  541. '69915dad1e84c6376a68c2967e4dab615ae0fd1faec44cc484828529463ccf72',
  542. 'b4ac6bec93e8598e7f0dadbcea5b',
  543. '404142434445464748494a4b4c4d4e4f',
  544. '101112131415161718191a1b1c'),
  545. # RFC3610
  546. ( '0001020304050607',
  547. '08090a0b0c0d0e0f101112131415161718191a1b1c1d1e',
  548. '588c979a61c663d2f066d0c2c0f989806d5f6b61dac384',
  549. '17e8d12cfdf926e0',
  550. 'c0c1c2c3c4c5c6c7c8c9cacbcccdcecf',
  551. '00000003020100a0a1a2a3a4a5'),
  552. (
  553. '0001020304050607',
  554. '08090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f',
  555. '72c91a36e135f8cf291ca894085c87e3cc15c439c9e43a3b',
  556. 'a091d56e10400916',
  557. 'c0c1c2c3c4c5c6c7c8c9cacbcccdcecf',
  558. '00000004030201a0a1a2a3a4a5'),
  559. ( '0001020304050607',
  560. '08090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20',
  561. '51b1e5f44a197d1da46b0f8e2d282ae871e838bb64da859657',
  562. '4adaa76fbd9fb0c5',
  563. 'c0c1c2c3c4c5c6c7c8c9cacbcccdcecf',
  564. '00000005040302A0A1A2A3A4A5'),
  565. ( '000102030405060708090a0b',
  566. '0c0d0e0f101112131415161718191a1b1c1d1e',
  567. 'a28c6865939a9a79faaa5c4c2a9d4a91cdac8c',
  568. '96c861b9c9e61ef1',
  569. 'c0c1c2c3c4c5c6c7c8c9cacbcccdcecf',
  570. '00000006050403a0a1a2a3a4a5'),
  571. ( '000102030405060708090a0b',
  572. '0c0d0e0f101112131415161718191a1b1c1d1e1f',
  573. 'dcf1fb7b5d9e23fb9d4e131253658ad86ebdca3e',
  574. '51e83f077d9c2d93',
  575. 'c0c1c2c3c4c5c6c7c8c9cacbcccdcecf',
  576. '00000007060504a0a1a2a3a4a5'),
  577. ( '000102030405060708090a0b',
  578. '0c0d0e0f101112131415161718191a1b1c1d1e1f20',
  579. '6fc1b011f006568b5171a42d953d469b2570a4bd87',
  580. '405a0443ac91cb94',
  581. 'c0c1c2c3c4c5c6c7c8c9cacbcccdcecf',
  582. '00000008070605a0a1a2a3a4a5'),
  583. ( '0001020304050607',
  584. '08090a0b0c0d0e0f101112131415161718191a1b1c1d1e',
  585. '0135d1b2c95f41d5d1d4fec185d166b8094e999dfed96c',
  586. '048c56602c97acbb7490',
  587. 'c0c1c2c3c4c5c6c7c8c9cacbcccdcecf',
  588. '00000009080706a0a1a2a3a4a5'),
  589. ( '0001020304050607',
  590. '08090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f',
  591. '7b75399ac0831dd2f0bbd75879a2fd8f6cae6b6cd9b7db24',
  592. 'c17b4433f434963f34b4',
  593. 'c0c1c2c3c4c5c6c7c8c9cacbcccdcecf',
  594. '0000000a090807a0a1a2a3a4a5'),
  595. ( '0001020304050607',
  596. '08090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20',
  597. '82531a60cc24945a4b8279181ab5c84df21ce7f9b73f42e197',
  598. 'ea9c07e56b5eb17e5f4e',
  599. 'c0c1c2c3c4c5c6c7c8c9cacbcccdcecf',
  600. '0000000b0a0908a0a1a2a3a4a5'),
  601. ( '000102030405060708090a0b',
  602. '0c0d0e0f101112131415161718191a1b1c1d1e',
  603. '07342594157785152b074098330abb141b947b',
  604. '566aa9406b4d999988dd',
  605. 'c0c1c2c3c4c5c6c7c8c9cacbcccdcecf',
  606. '0000000c0b0a09a0a1a2a3a4a5'),
  607. ( '000102030405060708090a0b',
  608. '0c0d0e0f101112131415161718191a1b1c1d1e1f',
  609. '676bb20380b0e301e8ab79590a396da78b834934',
  610. 'f53aa2e9107a8b6c022c',
  611. 'c0c1c2c3c4c5c6c7c8c9cacbcccdcecf',
  612. '0000000d0c0b0aa0a1a2a3a4a5'),
  613. ( '000102030405060708090a0b',
  614. '0c0d0e0f101112131415161718191a1b1c1d1e1f20',
  615. 'c0ffa0d6f05bdb67f24d43a4338d2aa4bed7b20e43',
  616. 'cd1aa31662e7ad65d6db',
  617. 'c0c1c2c3c4c5c6c7c8c9cacbcccdcecf',
  618. '0000000e0d0c0ba0a1a2a3a4a5'),
  619. ( '0be1a88bace018b1',
  620. '08e8cf97d820ea258460e96ad9cf5289054d895ceac47c',
  621. '4cb97f86a2a4689a877947ab8091ef5386a6ffbdd080f8',
  622. 'e78cf7cb0cddd7b3',
  623. 'd7828d13b2b0bdc325a76236df93cc6b',
  624. '00412b4ea9cdbe3c9696766cfa'),
  625. ( '63018f76dc8a1bcb',
  626. '9020ea6f91bdd85afa0039ba4baff9bfb79c7028949cd0ec',
  627. '4ccb1e7ca981befaa0726c55d378061298c85c92814abc33',
  628. 'c52ee81d7d77c08a',
  629. 'd7828d13b2b0bdc325a76236df93cc6b',
  630. '0033568ef7b2633c9696766cfa'),
  631. ( 'aa6cfa36cae86b40',
  632. 'b916e0eacc1c00d7dcec68ec0b3bbb1a02de8a2d1aa346132e',
  633. 'b1d23a2220ddc0ac900d9aa03c61fcf4a559a4417767089708',
  634. 'a776796edb723506',
  635. 'd7828d13b2b0bdc325a76236df93cc6b',
  636. '00103fe41336713c9696766cfa'),
  637. ( 'd0d0735c531e1becf049c244',
  638. '12daac5630efa5396f770ce1a66b21f7b2101c',
  639. '14d253c3967b70609b7cbb7c49916028324526',
  640. '9a6f49975bcadeaf',
  641. 'd7828d13b2b0bdc325a76236df93cc6b',
  642. '00764c63b8058e3c9696766cfa'),
  643. ( '77b60f011c03e1525899bcae',
  644. 'e88b6a46c78d63e52eb8c546efb5de6f75e9cc0d',
  645. '5545ff1a085ee2efbf52b2e04bee1e2336c73e3f',
  646. '762c0c7744fe7e3c',
  647. 'd7828d13b2b0bdc325a76236df93cc6b',
  648. '00f8b678094e3b3c9696766cfa'),
  649. ( 'cd9044d2b71fdb8120ea60c0',
  650. '6435acbafb11a82e2f071d7ca4a5ebd93a803ba87f',
  651. '009769ecabdf48625594c59251e6035722675e04c8',
  652. '47099e5ae0704551',
  653. 'd7828d13b2b0bdc325a76236df93cc6b',
  654. '00d560912d3f703c9696766cfa'),
  655. ( 'd85bc7e69f944fb8',
  656. '8a19b950bcf71a018e5e6701c91787659809d67dbedd18',
  657. 'bc218daa947427b6db386a99ac1aef23ade0b52939cb6a',
  658. '637cf9bec2408897c6ba',
  659. 'd7828d13b2b0bdc325a76236df93cc6b',
  660. '0042fff8f1951c3c9696766cfa'),
  661. ( '74a0ebc9069f5b37',
  662. '1761433c37c5a35fc1f39f406302eb907c6163be38c98437',
  663. '5810e6fd25874022e80361a478e3e9cf484ab04f447efff6',
  664. 'f0a477cc2fc9bf548944',
  665. 'd7828d13b2b0bdc325a76236df93cc6b',
  666. '00920f40e56cdc3c9696766cfa'),
  667. ( '44a3aa3aae6475ca',
  668. 'a434a8e58500c6e41530538862d686ea9e81301b5ae4226bfa',
  669. 'f2beed7bc5098e83feb5b31608f8e29c38819a89c8e776f154',
  670. '4d4151a4ed3a8b87b9ce',
  671. 'd7828d13b2b0bdc325a76236df93cc6b',
  672. '0027ca0c7120bc3c9696766cfa'),
  673. ( 'ec46bb63b02520c33c49fd70',
  674. 'b96b49e21d621741632875db7f6c9243d2d7c2',
  675. '31d750a09da3ed7fddd49a2032aabf17ec8ebf',
  676. '7d22c8088c666be5c197',
  677. 'd7828d13b2b0bdc325a76236df93cc6b',
  678. '005b8ccbcd9af83c9696766cfa'),
  679. ( '47a65ac78b3d594227e85e71',
  680. 'e2fcfbb880442c731bf95167c8ffd7895e337076',
  681. 'e882f1dbd38ce3eda7c23f04dd65071eb41342ac',
  682. 'df7e00dccec7ae52987d',
  683. 'd7828d13b2b0bdc325a76236df93cc6b',
  684. '003ebe94044b9a3c9696766cfa'),
  685. ( '6e37a6ef546d955d34ab6059',
  686. 'abf21c0b02feb88f856df4a37381bce3cc128517d4',
  687. 'f32905b88a641b04b9c9ffb58cc390900f3da12ab1',
  688. '6dce9e82efa16da62059',
  689. 'd7828d13b2b0bdc325a76236df93cc6b',
  690. '008d493b30ae8b3c9696766cfa'),
  691. ]
  692. test_vectors = [[unhexlify(x) for x in tv] for tv in test_vectors_hex]
  693. def runTest(self):
  694. for assoc_data, pt, ct, mac, key, nonce in self.test_vectors:
  695. # Encrypt
  696. cipher = AES.new(key, AES.MODE_CCM, nonce, mac_len=len(mac))
  697. cipher.update(assoc_data)
  698. ct2, mac2 = cipher.encrypt_and_digest(pt)
  699. self.assertEqual(ct, ct2)
  700. self.assertEqual(mac, mac2)
  701. # Decrypt
  702. cipher = AES.new(key, AES.MODE_CCM, nonce, mac_len=len(mac))
  703. cipher.update(assoc_data)
  704. pt2 = cipher.decrypt_and_verify(ct, mac)
  705. self.assertEqual(pt, pt2)
  706. class TestVectorsWycheproof(unittest.TestCase):
  707. def __init__(self, wycheproof_warnings, **extra_params):
  708. unittest.TestCase.__init__(self)
  709. self._wycheproof_warnings = wycheproof_warnings
  710. self._extra_params = extra_params
  711. self._id = "None"
  712. def setUp(self):
  713. def filter_tag(group):
  714. return group['tagSize'] // 8
  715. self.tv = load_test_vectors_wycheproof(("Cipher", "wycheproof"),
  716. "aes_ccm_test.json",
  717. "Wycheproof AES CCM",
  718. group_tag={'tag_size': filter_tag})
  719. def shortDescription(self):
  720. return self._id
  721. def warn(self, tv):
  722. if tv.warning and self._wycheproof_warnings:
  723. import warnings
  724. warnings.warn("Wycheproof warning: %s (%s)" % (self._id, tv.comment))
  725. def test_encrypt(self, tv):
  726. self._id = "Wycheproof Encrypt CCM Test #" + str(tv.id)
  727. try:
  728. cipher = AES.new(tv.key, AES.MODE_CCM, tv.iv, mac_len=tv.tag_size,
  729. **self._extra_params)
  730. except ValueError as e:
  731. if len(tv.iv) not in range(7, 13 + 1, 2) and "Length of parameter 'nonce'" in str(e):
  732. assert not tv.valid
  733. return
  734. if tv.tag_size not in range(4, 16 + 1, 2) and "Parameter 'mac_len'" in str(e):
  735. assert not tv.valid
  736. return
  737. raise e
  738. cipher.update(tv.aad)
  739. ct, tag = cipher.encrypt_and_digest(tv.msg)
  740. if tv.valid:
  741. self.assertEqual(ct, tv.ct)
  742. self.assertEqual(tag, tv.tag)
  743. self.warn(tv)
  744. def test_decrypt(self, tv):
  745. self._id = "Wycheproof Decrypt CCM Test #" + str(tv.id)
  746. try:
  747. cipher = AES.new(tv.key, AES.MODE_CCM, tv.iv, mac_len=tv.tag_size,
  748. **self._extra_params)
  749. except ValueError as e:
  750. if len(tv.iv) not in range(7, 13 + 1, 2) and "Length of parameter 'nonce'" in str(e):
  751. assert not tv.valid
  752. return
  753. if tv.tag_size not in range(4, 16 + 1, 2) and "Parameter 'mac_len'" in str(e):
  754. assert not tv.valid
  755. return
  756. raise e
  757. cipher.update(tv.aad)
  758. try:
  759. pt = cipher.decrypt_and_verify(tv.ct, tv.tag)
  760. except ValueError:
  761. assert not tv.valid
  762. else:
  763. assert tv.valid
  764. self.assertEqual(pt, tv.msg)
  765. self.warn(tv)
  766. def test_corrupt_decrypt(self, tv):
  767. self._id = "Wycheproof Corrupt Decrypt CCM Test #" + str(tv.id)
  768. if len(tv.iv) not in range(7, 13 + 1, 2) or len(tv.ct) == 0:
  769. return
  770. cipher = AES.new(tv.key, AES.MODE_CCM, tv.iv, mac_len=tv.tag_size,
  771. **self._extra_params)
  772. cipher.update(tv.aad)
  773. ct_corrupt = strxor(tv.ct, b"\x00" * (len(tv.ct) - 1) + b"\x01")
  774. self.assertRaises(ValueError, cipher.decrypt_and_verify, ct_corrupt, tv.tag)
  775. def runTest(self):
  776. for tv in self.tv:
  777. self.test_encrypt(tv)
  778. self.test_decrypt(tv)
  779. self.test_corrupt_decrypt(tv)
  780. def get_tests(config={}):
  781. wycheproof_warnings = config.get('wycheproof_warnings')
  782. tests = []
  783. tests += list_test_cases(CcmTests)
  784. tests += list_test_cases(CcmFSMTests)
  785. tests += [TestVectors()]
  786. tests += [TestVectorsWycheproof(wycheproof_warnings)]
  787. return tests
  788. if __name__ == '__main__':
  789. def suite():
  790. unittest.TestSuite(get_tests())
  791. unittest.main(defaultTest='suite')