test_CCM.py 38 KB

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