test_CCM.py 36 KB

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