test_CCM.py 37 KB

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