test_EAX.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  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, DES3
  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 EaxTests(unittest.TestCase):
  42. key_128 = get_tag_random("key_128", 16)
  43. key_192 = get_tag_random("key_192", 16)
  44. nonce_96 = get_tag_random("nonce_128", 12)
  45. data_128 = get_tag_random("data_128", 16)
  46. def test_loopback_128(self):
  47. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  48. pt = get_tag_random("plaintext", 16 * 100)
  49. ct = cipher.encrypt(pt)
  50. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  51. pt2 = cipher.decrypt(ct)
  52. self.assertEqual(pt, pt2)
  53. def test_loopback_64(self):
  54. cipher = DES3.new(self.key_192, DES3.MODE_EAX, nonce=self.nonce_96)
  55. pt = get_tag_random("plaintext", 8 * 100)
  56. ct = cipher.encrypt(pt)
  57. cipher = DES3.new(self.key_192, DES3.MODE_EAX, nonce=self.nonce_96)
  58. pt2 = cipher.decrypt(ct)
  59. self.assertEqual(pt, pt2)
  60. def test_nonce(self):
  61. # If not passed, the nonce is created randomly
  62. cipher = AES.new(self.key_128, AES.MODE_EAX)
  63. nonce1 = cipher.nonce
  64. cipher = AES.new(self.key_128, AES.MODE_EAX)
  65. nonce2 = cipher.nonce
  66. self.assertEqual(len(nonce1), 16)
  67. self.assertNotEqual(nonce1, nonce2)
  68. cipher = AES.new(self.key_128, AES.MODE_EAX, self.nonce_96)
  69. ct = cipher.encrypt(self.data_128)
  70. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  71. self.assertEquals(ct, cipher.encrypt(self.data_128))
  72. def test_nonce_must_be_bytes(self):
  73. self.assertRaises(TypeError, AES.new, self.key_128, AES.MODE_EAX,
  74. nonce=u'test12345678')
  75. def test_nonce_length(self):
  76. # nonce can be of any length (but not empty)
  77. self.assertRaises(ValueError, AES.new, self.key_128, AES.MODE_EAX,
  78. nonce=b"")
  79. for x in range(1, 128):
  80. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=bchr(1) * x)
  81. cipher.encrypt(bchr(1))
  82. def test_block_size_128(self):
  83. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  84. self.assertEqual(cipher.block_size, AES.block_size)
  85. def test_block_size_64(self):
  86. cipher = DES3.new(self.key_192, AES.MODE_EAX, nonce=self.nonce_96)
  87. self.assertEqual(cipher.block_size, DES3.block_size)
  88. def test_nonce_attribute(self):
  89. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  90. self.assertEqual(cipher.nonce, self.nonce_96)
  91. # By default, a 16 bytes long nonce is randomly generated
  92. nonce1 = AES.new(self.key_128, AES.MODE_EAX).nonce
  93. nonce2 = AES.new(self.key_128, AES.MODE_EAX).nonce
  94. self.assertEqual(len(nonce1), 16)
  95. self.assertNotEqual(nonce1, nonce2)
  96. def test_unknown_parameters(self):
  97. self.assertRaises(TypeError, AES.new, self.key_128, AES.MODE_EAX,
  98. self.nonce_96, 7)
  99. self.assertRaises(TypeError, AES.new, self.key_128, AES.MODE_EAX,
  100. nonce=self.nonce_96, unknown=7)
  101. # But some are only known by the base cipher
  102. # (e.g. use_aesni consumed by the AES module)
  103. AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96,
  104. use_aesni=False)
  105. def test_null_encryption_decryption(self):
  106. for func in "encrypt", "decrypt":
  107. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  108. result = getattr(cipher, func)(b"")
  109. self.assertEqual(result, b"")
  110. def test_either_encrypt_or_decrypt(self):
  111. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  112. cipher.encrypt(b"")
  113. self.assertRaises(TypeError, cipher.decrypt, b"")
  114. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  115. cipher.decrypt(b"")
  116. self.assertRaises(TypeError, cipher.encrypt, b"")
  117. def test_data_must_be_bytes(self):
  118. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  119. self.assertRaises(TypeError, cipher.encrypt, u'test1234567890-*')
  120. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  121. self.assertRaises(TypeError, cipher.decrypt, u'test1234567890-*')
  122. def test_mac_len(self):
  123. # Invalid MAC length
  124. self.assertRaises(ValueError, AES.new, self.key_128, AES.MODE_EAX,
  125. nonce=self.nonce_96, mac_len=3)
  126. self.assertRaises(ValueError, AES.new, self.key_128, AES.MODE_EAX,
  127. nonce=self.nonce_96, mac_len=16+1)
  128. # Valid MAC length
  129. for mac_len in range(5, 16 + 1):
  130. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96,
  131. mac_len=mac_len)
  132. _, mac = cipher.encrypt_and_digest(self.data_128)
  133. self.assertEqual(len(mac), mac_len)
  134. # Default MAC length
  135. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  136. _, mac = cipher.encrypt_and_digest(self.data_128)
  137. self.assertEqual(len(mac), 16)
  138. def test_invalid_mac(self):
  139. from tls.Crypto.Util.strxor import strxor_c
  140. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  141. ct, mac = cipher.encrypt_and_digest(self.data_128)
  142. invalid_mac = strxor_c(mac, 0x01)
  143. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  144. self.assertRaises(ValueError, cipher.decrypt_and_verify, ct,
  145. invalid_mac)
  146. def test_hex_mac(self):
  147. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  148. mac_hex = cipher.hexdigest()
  149. self.assertEqual(cipher.digest(), unhexlify(mac_hex))
  150. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  151. cipher.hexverify(mac_hex)
  152. def test_message_chunks(self):
  153. # Validate that both associated data and plaintext/ciphertext
  154. # can be broken up in chunks of arbitrary length
  155. auth_data = get_tag_random("authenticated data", 127)
  156. plaintext = get_tag_random("plaintext", 127)
  157. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  158. cipher.update(auth_data)
  159. ciphertext, ref_mac = cipher.encrypt_and_digest(plaintext)
  160. def break_up(data, chunk_length):
  161. return [data[i:i+chunk_length] for i in range(0, len(data),
  162. chunk_length)]
  163. # Encryption
  164. for chunk_length in 1, 2, 3, 7, 10, 13, 16, 40, 80, 128:
  165. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  166. for chunk in break_up(auth_data, chunk_length):
  167. cipher.update(chunk)
  168. pt2 = b""
  169. for chunk in break_up(ciphertext, chunk_length):
  170. pt2 += cipher.decrypt(chunk)
  171. self.assertEqual(plaintext, pt2)
  172. cipher.verify(ref_mac)
  173. # Decryption
  174. for chunk_length in 1, 2, 3, 7, 10, 13, 16, 40, 80, 128:
  175. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  176. for chunk in break_up(auth_data, chunk_length):
  177. cipher.update(chunk)
  178. ct2 = b""
  179. for chunk in break_up(plaintext, chunk_length):
  180. ct2 += cipher.encrypt(chunk)
  181. self.assertEqual(ciphertext, ct2)
  182. self.assertEquals(cipher.digest(), ref_mac)
  183. def test_bytearray(self):
  184. # Encrypt
  185. key_ba = bytearray(self.key_128)
  186. nonce_ba = bytearray(self.nonce_96)
  187. header_ba = bytearray(self.data_128)
  188. data_ba = bytearray(self.data_128)
  189. cipher1 = AES.new(self.key_128,
  190. AES.MODE_EAX,
  191. nonce=self.nonce_96)
  192. cipher1.update(self.data_128)
  193. ct = cipher1.encrypt(self.data_128)
  194. tag = cipher1.digest()
  195. cipher2 = AES.new(key_ba,
  196. AES.MODE_EAX,
  197. nonce=nonce_ba)
  198. key_ba[:3] = b'\xFF\xFF\xFF'
  199. nonce_ba[:3] = b'\xFF\xFF\xFF'
  200. cipher2.update(header_ba)
  201. header_ba[:3] = b'\xFF\xFF\xFF'
  202. ct_test = cipher2.encrypt(data_ba)
  203. data_ba[:3] = b'\x99\x99\x99'
  204. tag_test = cipher2.digest()
  205. self.assertEqual(ct, ct_test)
  206. self.assertEqual(tag, tag_test)
  207. self.assertEqual(cipher1.nonce, cipher2.nonce)
  208. # Decrypt
  209. key_ba = bytearray(self.key_128)
  210. nonce_ba = bytearray(self.nonce_96)
  211. header_ba = bytearray(self.data_128)
  212. ct_ba = bytearray(ct)
  213. tag_ba = bytearray(tag)
  214. del data_ba
  215. cipher3 = AES.new(key_ba,
  216. AES.MODE_EAX,
  217. nonce=nonce_ba)
  218. key_ba[:3] = b'\xFF\xFF\xFF'
  219. nonce_ba[:3] = b'\xFF\xFF\xFF'
  220. cipher3.update(header_ba)
  221. header_ba[:3] = b'\xFF\xFF\xFF'
  222. pt_test = cipher3.decrypt(ct_ba)
  223. ct_ba[:3] = b'\xFF\xFF\xFF'
  224. cipher3.verify(tag_ba)
  225. self.assertEqual(pt_test, self.data_128)
  226. def test_memoryview(self):
  227. # Encrypt
  228. key_mv = memoryview(bytearray(self.key_128))
  229. nonce_mv = memoryview(bytearray(self.nonce_96))
  230. header_mv = memoryview(bytearray(self.data_128))
  231. data_mv = memoryview(bytearray(self.data_128))
  232. cipher1 = AES.new(self.key_128,
  233. AES.MODE_EAX,
  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_mv,
  239. AES.MODE_EAX,
  240. nonce=nonce_mv)
  241. key_mv[:3] = b'\xFF\xFF\xFF'
  242. nonce_mv[:3] = b'\xFF\xFF\xFF'
  243. cipher2.update(header_mv)
  244. header_mv[:3] = b'\xFF\xFF\xFF'
  245. ct_test = cipher2.encrypt(data_mv)
  246. data_mv[:3] = b'\x99\x99\x99'
  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_mv = memoryview(bytearray(self.key_128))
  253. nonce_mv = memoryview(bytearray(self.nonce_96))
  254. header_mv = memoryview(bytearray(self.data_128))
  255. ct_mv = memoryview(bytearray(ct))
  256. tag_mv = memoryview(bytearray(tag))
  257. del data_mv
  258. cipher3 = AES.new(key_mv,
  259. AES.MODE_EAX,
  260. nonce=nonce_mv)
  261. key_mv[:3] = b'\xFF\xFF\xFF'
  262. nonce_mv[:3] = b'\xFF\xFF\xFF'
  263. cipher3.update(header_mv)
  264. header_mv[:3] = b'\xFF\xFF\xFF'
  265. pt_test = cipher3.decrypt(ct_mv)
  266. ct_mv[:3] = b'\x99\x99\x99'
  267. cipher3.verify(tag_mv)
  268. self.assertEqual(pt_test, self.data_128)
  269. def test_output_param(self):
  270. pt = b'5' * 16
  271. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  272. ct = cipher.encrypt(pt)
  273. tag = cipher.digest()
  274. output = bytearray(16)
  275. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  276. res = cipher.encrypt(pt, output=output)
  277. self.assertEqual(ct, output)
  278. self.assertEqual(res, None)
  279. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  280. res = cipher.decrypt(ct, output=output)
  281. self.assertEqual(pt, output)
  282. self.assertEqual(res, None)
  283. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  284. res, tag_out = cipher.encrypt_and_digest(pt, output=output)
  285. self.assertEqual(ct, output)
  286. self.assertEqual(res, None)
  287. self.assertEqual(tag, tag_out)
  288. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  289. res = cipher.decrypt_and_verify(ct, tag, output=output)
  290. self.assertEqual(pt, output)
  291. self.assertEqual(res, None)
  292. def test_output_param_memoryview(self):
  293. pt = b'5' * 16
  294. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  295. ct = cipher.encrypt(pt)
  296. output = memoryview(bytearray(16))
  297. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  298. cipher.encrypt(pt, output=output)
  299. self.assertEqual(ct, output)
  300. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  301. cipher.decrypt(ct, output=output)
  302. self.assertEqual(pt, output)
  303. def test_output_param_neg(self):
  304. pt = b'5' * 16
  305. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  306. ct = cipher.encrypt(pt)
  307. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  308. self.assertRaises(TypeError, cipher.encrypt, pt, output=b'0'*16)
  309. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  310. self.assertRaises(TypeError, cipher.decrypt, ct, output=b'0'*16)
  311. shorter_output = bytearray(15)
  312. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  313. self.assertRaises(ValueError, cipher.encrypt, pt, output=shorter_output)
  314. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  315. self.assertRaises(ValueError, cipher.decrypt, ct, output=shorter_output)
  316. import sys
  317. if sys.version[:3] == "2.6":
  318. del test_memoryview
  319. del test_output_param_memoryview
  320. class EaxFSMTests(unittest.TestCase):
  321. key_128 = get_tag_random("key_128", 16)
  322. nonce_96 = get_tag_random("nonce_128", 12)
  323. data_128 = get_tag_random("data_128", 16)
  324. def test_valid_init_encrypt_decrypt_digest_verify(self):
  325. # No authenticated data, fixed plaintext
  326. # Verify path INIT->ENCRYPT->DIGEST
  327. cipher = AES.new(self.key_128, AES.MODE_EAX,
  328. nonce=self.nonce_96)
  329. ct = cipher.encrypt(self.data_128)
  330. mac = cipher.digest()
  331. # Verify path INIT->DECRYPT->VERIFY
  332. cipher = AES.new(self.key_128, AES.MODE_EAX,
  333. nonce=self.nonce_96)
  334. cipher.decrypt(ct)
  335. cipher.verify(mac)
  336. def test_valid_init_update_digest_verify(self):
  337. # No plaintext, fixed authenticated data
  338. # Verify path INIT->UPDATE->DIGEST
  339. cipher = AES.new(self.key_128, AES.MODE_EAX,
  340. nonce=self.nonce_96)
  341. cipher.update(self.data_128)
  342. mac = cipher.digest()
  343. # Verify path INIT->UPDATE->VERIFY
  344. cipher = AES.new(self.key_128, AES.MODE_EAX,
  345. nonce=self.nonce_96)
  346. cipher.update(self.data_128)
  347. cipher.verify(mac)
  348. def test_valid_full_path(self):
  349. # Fixed authenticated data, fixed plaintext
  350. # Verify path INIT->UPDATE->ENCRYPT->DIGEST
  351. cipher = AES.new(self.key_128, AES.MODE_EAX,
  352. nonce=self.nonce_96)
  353. cipher.update(self.data_128)
  354. ct = cipher.encrypt(self.data_128)
  355. mac = cipher.digest()
  356. # Verify path INIT->UPDATE->DECRYPT->VERIFY
  357. cipher = AES.new(self.key_128, AES.MODE_EAX,
  358. nonce=self.nonce_96)
  359. cipher.update(self.data_128)
  360. cipher.decrypt(ct)
  361. cipher.verify(mac)
  362. def test_valid_init_digest(self):
  363. # Verify path INIT->DIGEST
  364. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  365. cipher.digest()
  366. def test_valid_init_verify(self):
  367. # Verify path INIT->VERIFY
  368. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  369. mac = cipher.digest()
  370. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  371. cipher.verify(mac)
  372. def test_valid_multiple_encrypt_or_decrypt(self):
  373. for method_name in "encrypt", "decrypt":
  374. for auth_data in (None, b"333", self.data_128,
  375. self.data_128 + b"3"):
  376. if auth_data is None:
  377. assoc_len = None
  378. else:
  379. assoc_len = len(auth_data)
  380. cipher = AES.new(self.key_128, AES.MODE_EAX,
  381. nonce=self.nonce_96)
  382. if auth_data is not None:
  383. cipher.update(auth_data)
  384. method = getattr(cipher, method_name)
  385. method(self.data_128)
  386. method(self.data_128)
  387. method(self.data_128)
  388. method(self.data_128)
  389. def test_valid_multiple_digest_or_verify(self):
  390. # Multiple calls to digest
  391. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  392. cipher.update(self.data_128)
  393. first_mac = cipher.digest()
  394. for x in range(4):
  395. self.assertEqual(first_mac, cipher.digest())
  396. # Multiple calls to verify
  397. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  398. cipher.update(self.data_128)
  399. for x in range(5):
  400. cipher.verify(first_mac)
  401. def test_valid_encrypt_and_digest_decrypt_and_verify(self):
  402. # encrypt_and_digest
  403. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  404. cipher.update(self.data_128)
  405. ct, mac = cipher.encrypt_and_digest(self.data_128)
  406. # decrypt_and_verify
  407. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  408. cipher.update(self.data_128)
  409. pt = cipher.decrypt_and_verify(ct, mac)
  410. self.assertEqual(self.data_128, pt)
  411. def test_invalid_mixing_encrypt_decrypt(self):
  412. # Once per method, with or without assoc. data
  413. for method1_name, method2_name in (("encrypt", "decrypt"),
  414. ("decrypt", "encrypt")):
  415. for assoc_data_present in (True, False):
  416. cipher = AES.new(self.key_128, AES.MODE_EAX,
  417. nonce=self.nonce_96)
  418. if assoc_data_present:
  419. cipher.update(self.data_128)
  420. getattr(cipher, method1_name)(self.data_128)
  421. self.assertRaises(TypeError, getattr(cipher, method2_name),
  422. self.data_128)
  423. def test_invalid_encrypt_or_update_after_digest(self):
  424. for method_name in "encrypt", "update":
  425. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  426. cipher.encrypt(self.data_128)
  427. cipher.digest()
  428. self.assertRaises(TypeError, getattr(cipher, method_name),
  429. self.data_128)
  430. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  431. cipher.encrypt_and_digest(self.data_128)
  432. def test_invalid_decrypt_or_update_after_verify(self):
  433. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  434. ct = cipher.encrypt(self.data_128)
  435. mac = cipher.digest()
  436. for method_name in "decrypt", "update":
  437. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  438. cipher.decrypt(ct)
  439. cipher.verify(mac)
  440. self.assertRaises(TypeError, getattr(cipher, method_name),
  441. self.data_128)
  442. cipher = AES.new(self.key_128, AES.MODE_EAX, nonce=self.nonce_96)
  443. cipher.decrypt_and_verify(ct, mac)
  444. self.assertRaises(TypeError, getattr(cipher, method_name),
  445. self.data_128)
  446. class TestVectorsPaper(unittest.TestCase):
  447. """Class exercising the EAX test vectors found in
  448. http://www.cs.ucdavis.edu/~rogaway/papers/eax.pdf"""
  449. test_vectors_hex = [
  450. ( '6bfb914fd07eae6b',
  451. '',
  452. '',
  453. 'e037830e8389f27b025a2d6527e79d01',
  454. '233952dee4d5ed5f9b9c6d6ff80ff478',
  455. '62EC67F9C3A4A407FCB2A8C49031A8B3'
  456. ),
  457. (
  458. 'fa3bfd4806eb53fa',
  459. 'f7fb',
  460. '19dd',
  461. '5c4c9331049d0bdab0277408f67967e5',
  462. '91945d3f4dcbee0bf45ef52255f095a4',
  463. 'BECAF043B0A23D843194BA972C66DEBD'
  464. ),
  465. ( '234a3463c1264ac6',
  466. '1a47cb4933',
  467. 'd851d5bae0',
  468. '3a59f238a23e39199dc9266626c40f80',
  469. '01f74ad64077f2e704c0f60ada3dd523',
  470. '70C3DB4F0D26368400A10ED05D2BFF5E'
  471. ),
  472. (
  473. '33cce2eabff5a79d',
  474. '481c9e39b1',
  475. '632a9d131a',
  476. 'd4c168a4225d8e1ff755939974a7bede',
  477. 'd07cf6cbb7f313bdde66b727afd3c5e8',
  478. '8408DFFF3C1A2B1292DC199E46B7D617'
  479. ),
  480. (
  481. 'aeb96eaebe2970e9',
  482. '40d0c07da5e4',
  483. '071dfe16c675',
  484. 'cb0677e536f73afe6a14b74ee49844dd',
  485. '35b6d0580005bbc12b0587124557d2c2',
  486. 'FDB6B06676EEDC5C61D74276E1F8E816'
  487. ),
  488. (
  489. 'd4482d1ca78dce0f',
  490. '4de3b35c3fc039245bd1fb7d',
  491. '835bb4f15d743e350e728414',
  492. 'abb8644fd6ccb86947c5e10590210a4f',
  493. 'bd8e6e11475e60b268784c38c62feb22',
  494. '6EAC5C93072D8E8513F750935E46DA1B'
  495. ),
  496. (
  497. '65d2017990d62528',
  498. '8b0a79306c9ce7ed99dae4f87f8dd61636',
  499. '02083e3979da014812f59f11d52630da30',
  500. '137327d10649b0aa6e1c181db617d7f2',
  501. '7c77d6e813bed5ac98baa417477a2e7d',
  502. '1A8C98DCD73D38393B2BF1569DEEFC19'
  503. ),
  504. (
  505. '54b9f04e6a09189a',
  506. '1bda122bce8a8dbaf1877d962b8592dd2d56',
  507. '2ec47b2c4954a489afc7ba4897edcdae8cc3',
  508. '3b60450599bd02c96382902aef7f832a',
  509. '5fff20cafab119ca2fc73549e20f5b0d',
  510. 'DDE59B97D722156D4D9AFF2BC7559826'
  511. ),
  512. (
  513. '899a175897561d7e',
  514. '6cf36720872b8513f6eab1a8a44438d5ef11',
  515. '0de18fd0fdd91e7af19f1d8ee8733938b1e8',
  516. 'e7f6d2231618102fdb7fe55ff1991700',
  517. 'a4a4782bcffd3ec5e7ef6d8c34a56123',
  518. 'B781FCF2F75FA5A8DE97A9CA48E522EC'
  519. ),
  520. (
  521. '126735fcc320d25a',
  522. 'ca40d7446e545ffaed3bd12a740a659ffbbb3ceab7',
  523. 'cb8920f87a6c75cff39627b56e3ed197c552d295a7',
  524. 'cfc46afc253b4652b1af3795b124ab6e',
  525. '8395fcf1e95bebd697bd010bc766aac3',
  526. '22E7ADD93CFC6393C57EC0B3C17D6B44'
  527. ),
  528. ]
  529. test_vectors = [[unhexlify(x) for x in tv] for tv in test_vectors_hex]
  530. def runTest(self):
  531. for assoc_data, pt, ct, mac, key, nonce in self.test_vectors:
  532. # Encrypt
  533. cipher = AES.new(key, AES.MODE_EAX, nonce, mac_len=len(mac))
  534. cipher.update(assoc_data)
  535. ct2, mac2 = cipher.encrypt_and_digest(pt)
  536. self.assertEqual(ct, ct2)
  537. self.assertEqual(mac, mac2)
  538. # Decrypt
  539. cipher = AES.new(key, AES.MODE_EAX, nonce, mac_len=len(mac))
  540. cipher.update(assoc_data)
  541. pt2 = cipher.decrypt_and_verify(ct, mac)
  542. self.assertEqual(pt, pt2)
  543. class TestVectorsWycheproof(unittest.TestCase):
  544. def __init__(self, wycheproof_warnings):
  545. unittest.TestCase.__init__(self)
  546. self._wycheproof_warnings = wycheproof_warnings
  547. self._id = "None"
  548. def setUp(self):
  549. comps = "Crypto.SelfTest.Cipher.test_vectors.wycheproof".split(".")
  550. with open(pycryptodome_filename(comps, "aes_eax_test.json"), "rt") as file_in:
  551. tv_tree = json.load(file_in)
  552. class TestVector(object):
  553. pass
  554. self.tv = []
  555. for group in tv_tree['testGroups']:
  556. tag_size = group['tagSize'] // 8
  557. for test in group['tests']:
  558. tv = TestVector()
  559. tv.tag_size = tag_size
  560. tv.id = test['tcId']
  561. tv.comment = test['comment']
  562. for attr in 'key', 'iv', 'aad', 'msg', 'ct', 'tag':
  563. setattr(tv, attr, unhexlify(test[attr]))
  564. tv.valid = test['result'] != "invalid"
  565. tv.warning = test['result'] == "acceptable"
  566. self.tv.append(tv)
  567. def shortDescription(self):
  568. return self._id
  569. def warn(self, tv):
  570. if tv.warning and self._wycheproof_warnings:
  571. import warnings
  572. warnings.warn("Wycheproof warning: %s (%s)" % (self._id, tv.comment))
  573. def test_encrypt(self, tv):
  574. self._id = "Wycheproof Encrypt EAX Test #" + str(tv.id)
  575. try:
  576. cipher = AES.new(tv.key, AES.MODE_EAX, tv.iv, mac_len=tv.tag_size)
  577. except ValueError as e:
  578. assert len(tv.iv) == 0 and "Nonce cannot be empty" in str(e)
  579. return
  580. cipher.update(tv.aad)
  581. ct, tag = cipher.encrypt_and_digest(tv.msg)
  582. if tv.valid:
  583. self.assertEqual(ct, tv.ct)
  584. self.assertEqual(tag, tv.tag)
  585. self.warn(tv)
  586. def test_decrypt(self, tv):
  587. self._id = "Wycheproof Decrypt EAX Test #" + str(tv.id)
  588. try:
  589. cipher = AES.new(tv.key, AES.MODE_EAX, tv.iv, mac_len=tv.tag_size)
  590. except ValueError as e:
  591. assert len(tv.iv) == 0 and "Nonce cannot be empty" in str(e)
  592. return
  593. cipher.update(tv.aad)
  594. try:
  595. pt = cipher.decrypt_and_verify(tv.ct, tv.tag)
  596. except ValueError:
  597. assert not tv.valid
  598. else:
  599. assert tv.valid
  600. self.assertEqual(pt, tv.msg)
  601. self.warn(tv)
  602. def test_corrupt_decrypt(self, tv):
  603. self._id = "Wycheproof Corrupt Decrypt EAX Test #" + str(tv.id)
  604. if len(tv.iv) == 0 or len(tv.ct) < 1:
  605. return
  606. cipher = AES.new(tv.key, AES.MODE_EAX, tv.iv, mac_len=tv.tag_size)
  607. cipher.update(tv.aad)
  608. ct_corrupt = strxor(tv.ct, b"\x00" * (len(tv.ct) - 1) + b"\x01")
  609. self.assertRaises(ValueError, cipher.decrypt_and_verify, ct_corrupt, tv.tag)
  610. def runTest(self):
  611. for tv in self.tv:
  612. self.test_encrypt(tv)
  613. self.test_decrypt(tv)
  614. self.test_corrupt_decrypt(tv)
  615. class TestOtherCiphers(unittest.TestCase):
  616. @classmethod
  617. def create_test(cls, name, factory, key_size):
  618. def test_template(self, factory=factory, key_size=key_size):
  619. cipher = factory.new(get_tag_random("cipher", key_size),
  620. factory.MODE_EAX,
  621. nonce=b"nonce")
  622. ct, mac = cipher.encrypt_and_digest(b"plaintext")
  623. cipher = factory.new(get_tag_random("cipher", key_size),
  624. factory.MODE_EAX,
  625. nonce=b"nonce")
  626. pt2 = cipher.decrypt_and_verify(ct, mac)
  627. self.assertEqual(b"plaintext", pt2)
  628. setattr(cls, "test_" + name, test_template)
  629. from tls.Crypto.Cipher import DES, DES3, ARC2, CAST, Blowfish
  630. TestOtherCiphers.create_test("DES_" + str(DES.key_size), DES, DES.key_size)
  631. for ks in DES3.key_size:
  632. TestOtherCiphers.create_test("DES3_" + str(ks), DES3, ks)
  633. for ks in ARC2.key_size:
  634. TestOtherCiphers.create_test("ARC2_" + str(ks), ARC2, ks)
  635. for ks in CAST.key_size:
  636. TestOtherCiphers.create_test("CAST_" + str(ks), CAST, ks)
  637. for ks in Blowfish.key_size:
  638. TestOtherCiphers.create_test("Blowfish_" + str(ks), Blowfish, ks)
  639. def get_tests(config={}):
  640. wycheproof_warnings = config.get('wycheproof_warnings')
  641. tests = []
  642. tests += list_test_cases(EaxTests)
  643. tests += list_test_cases(EaxFSMTests)
  644. tests += [ TestVectorsPaper() ]
  645. tests += [ TestVectorsWycheproof(wycheproof_warnings) ]
  646. tests += list_test_cases(TestOtherCiphers)
  647. return tests
  648. if __name__ == '__main__':
  649. suite = lambda: unittest.TestSuite(get_tests())
  650. unittest.main(defaultTest='suite')