test_ChaCha20_Poly1305.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  1. # ===================================================================
  2. #
  3. # Copyright (c) 2018, Helder Eijs <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 Cryptodome.SelfTest.st_common import list_test_cases
  34. from Cryptodome.Util.py3compat import tobytes, _memoryview
  35. from Cryptodome.Cipher import ChaCha20_Poly1305
  36. from Cryptodome.Hash import SHAKE128
  37. from Cryptodome.Util._file_system import pycryptodome_filename
  38. from Cryptodome.Util.strxor import strxor
  39. def get_tag_random(tag, length):
  40. return SHAKE128.new(data=tobytes(tag)).read(length)
  41. class ChaCha20Poly1305Tests(unittest.TestCase):
  42. key_256 = get_tag_random("key_256", 32)
  43. nonce_96 = get_tag_random("nonce_96", 12)
  44. data_128 = get_tag_random("data_128", 16)
  45. def test_loopback(self):
  46. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  47. nonce=self.nonce_96)
  48. pt = get_tag_random("plaintext", 16 * 100)
  49. ct = cipher.encrypt(pt)
  50. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  51. nonce=self.nonce_96)
  52. pt2 = cipher.decrypt(ct)
  53. self.assertEqual(pt, pt2)
  54. def test_nonce(self):
  55. # Nonce can only be 8 or 12 bytes
  56. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  57. nonce=b'H' * 8)
  58. self.assertEqual(len(cipher.nonce), 8)
  59. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  60. nonce=b'H' * 12)
  61. self.assertEqual(len(cipher.nonce), 12)
  62. # If not passed, the nonce is created randomly
  63. cipher = ChaCha20_Poly1305.new(key=self.key_256)
  64. nonce1 = cipher.nonce
  65. cipher = ChaCha20_Poly1305.new(key=self.key_256)
  66. nonce2 = cipher.nonce
  67. self.assertEqual(len(nonce1), 12)
  68. self.assertNotEqual(nonce1, nonce2)
  69. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  70. nonce=self.nonce_96)
  71. ct = cipher.encrypt(self.data_128)
  72. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  73. nonce=self.nonce_96)
  74. self.assertEquals(ct, cipher.encrypt(self.data_128))
  75. def test_nonce_must_be_bytes(self):
  76. self.assertRaises(TypeError,
  77. ChaCha20_Poly1305.new,
  78. key=self.key_256,
  79. nonce=u'test12345678')
  80. def test_nonce_length(self):
  81. # nonce can only be 8 or 12 bytes long
  82. self.assertRaises(ValueError,
  83. ChaCha20_Poly1305.new,
  84. key=self.key_256,
  85. nonce=b'0' * 7)
  86. self.assertRaises(ValueError,
  87. ChaCha20_Poly1305.new,
  88. key=self.key_256,
  89. nonce=b'')
  90. def test_block_size(self):
  91. # Not based on block ciphers
  92. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  93. nonce=self.nonce_96)
  94. self.failIf(hasattr(cipher, 'block_size'))
  95. def test_nonce_attribute(self):
  96. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  97. nonce=self.nonce_96)
  98. self.assertEqual(cipher.nonce, self.nonce_96)
  99. # By default, a 12 bytes long nonce is randomly generated
  100. nonce1 = ChaCha20_Poly1305.new(key=self.key_256).nonce
  101. nonce2 = ChaCha20_Poly1305.new(key=self.key_256).nonce
  102. self.assertEqual(len(nonce1), 12)
  103. self.assertNotEqual(nonce1, nonce2)
  104. def test_unknown_parameters(self):
  105. self.assertRaises(TypeError,
  106. ChaCha20_Poly1305.new,
  107. key=self.key_256,
  108. param=9)
  109. def test_null_encryption_decryption(self):
  110. for func in "encrypt", "decrypt":
  111. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  112. nonce=self.nonce_96)
  113. result = getattr(cipher, func)(b"")
  114. self.assertEqual(result, b"")
  115. def test_either_encrypt_or_decrypt(self):
  116. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  117. nonce=self.nonce_96)
  118. cipher.encrypt(b"")
  119. self.assertRaises(TypeError, cipher.decrypt, b"")
  120. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  121. nonce=self.nonce_96)
  122. cipher.decrypt(b"")
  123. self.assertRaises(TypeError, cipher.encrypt, b"")
  124. def test_data_must_be_bytes(self):
  125. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  126. nonce=self.nonce_96)
  127. self.assertRaises(TypeError, cipher.encrypt, u'test1234567890-*')
  128. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  129. nonce=self.nonce_96)
  130. self.assertRaises(TypeError, cipher.decrypt, u'test1234567890-*')
  131. def test_mac_len(self):
  132. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  133. nonce=self.nonce_96)
  134. _, mac = cipher.encrypt_and_digest(self.data_128)
  135. self.assertEqual(len(mac), 16)
  136. def test_invalid_mac(self):
  137. from Cryptodome.Util.strxor import strxor_c
  138. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  139. nonce=self.nonce_96)
  140. ct, mac = cipher.encrypt_and_digest(self.data_128)
  141. invalid_mac = strxor_c(mac, 0x01)
  142. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  143. nonce=self.nonce_96)
  144. self.assertRaises(ValueError, cipher.decrypt_and_verify, ct,
  145. invalid_mac)
  146. def test_hex_mac(self):
  147. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  148. nonce=self.nonce_96)
  149. mac_hex = cipher.hexdigest()
  150. self.assertEqual(cipher.digest(), unhexlify(mac_hex))
  151. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  152. nonce=self.nonce_96)
  153. cipher.hexverify(mac_hex)
  154. def test_message_chunks(self):
  155. # Validate that both associated data and plaintext/ciphertext
  156. # can be broken up in chunks of arbitrary length
  157. auth_data = get_tag_random("authenticated data", 127)
  158. plaintext = get_tag_random("plaintext", 127)
  159. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  160. nonce=self.nonce_96)
  161. cipher.update(auth_data)
  162. ciphertext, ref_mac = cipher.encrypt_and_digest(plaintext)
  163. def break_up(data, chunk_length):
  164. return [data[i:i+chunk_length] for i in range(0, len(data),
  165. chunk_length)]
  166. # Encryption
  167. for chunk_length in 1, 2, 3, 7, 10, 13, 16, 40, 80, 128:
  168. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  169. nonce=self.nonce_96)
  170. for chunk in break_up(auth_data, chunk_length):
  171. cipher.update(chunk)
  172. pt2 = b""
  173. for chunk in break_up(ciphertext, chunk_length):
  174. pt2 += cipher.decrypt(chunk)
  175. self.assertEqual(plaintext, pt2)
  176. cipher.verify(ref_mac)
  177. # Decryption
  178. for chunk_length in 1, 2, 3, 7, 10, 13, 16, 40, 80, 128:
  179. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  180. nonce=self.nonce_96)
  181. for chunk in break_up(auth_data, chunk_length):
  182. cipher.update(chunk)
  183. ct2 = b""
  184. for chunk in break_up(plaintext, chunk_length):
  185. ct2 += cipher.encrypt(chunk)
  186. self.assertEqual(ciphertext, ct2)
  187. self.assertEquals(cipher.digest(), ref_mac)
  188. def test_bytearray(self):
  189. # Encrypt
  190. key_ba = bytearray(self.key_256)
  191. nonce_ba = bytearray(self.nonce_96)
  192. header_ba = bytearray(self.data_128)
  193. data_ba = bytearray(self.data_128)
  194. cipher1 = ChaCha20_Poly1305.new(key=self.key_256,
  195. nonce=self.nonce_96)
  196. cipher1.update(self.data_128)
  197. ct = cipher1.encrypt(self.data_128)
  198. tag = cipher1.digest()
  199. cipher2 = ChaCha20_Poly1305.new(key=self.key_256,
  200. nonce=self.nonce_96)
  201. key_ba[:3] = b'\xFF\xFF\xFF'
  202. nonce_ba[:3] = b'\xFF\xFF\xFF'
  203. cipher2.update(header_ba)
  204. header_ba[:3] = b'\xFF\xFF\xFF'
  205. ct_test = cipher2.encrypt(data_ba)
  206. data_ba[:3] = b'\x99\x99\x99'
  207. tag_test = cipher2.digest()
  208. self.assertEqual(ct, ct_test)
  209. self.assertEqual(tag, tag_test)
  210. self.assertEqual(cipher1.nonce, cipher2.nonce)
  211. # Decrypt
  212. key_ba = bytearray(self.key_256)
  213. nonce_ba = bytearray(self.nonce_96)
  214. header_ba = bytearray(self.data_128)
  215. ct_ba = bytearray(ct)
  216. tag_ba = bytearray(tag)
  217. del data_ba
  218. cipher3 = ChaCha20_Poly1305.new(key=self.key_256,
  219. nonce=self.nonce_96)
  220. key_ba[:3] = b'\xFF\xFF\xFF'
  221. nonce_ba[:3] = b'\xFF\xFF\xFF'
  222. cipher3.update(header_ba)
  223. header_ba[:3] = b'\xFF\xFF\xFF'
  224. pt_test = cipher3.decrypt(ct_ba)
  225. ct_ba[:3] = b'\xFF\xFF\xFF'
  226. cipher3.verify(tag_ba)
  227. self.assertEqual(pt_test, self.data_128)
  228. def test_memoryview(self):
  229. # Encrypt
  230. key_mv = memoryview(bytearray(self.key_256))
  231. nonce_mv = memoryview(bytearray(self.nonce_96))
  232. header_mv = memoryview(bytearray(self.data_128))
  233. data_mv = memoryview(bytearray(self.data_128))
  234. cipher1 = ChaCha20_Poly1305.new(key=self.key_256,
  235. nonce=self.nonce_96)
  236. cipher1.update(self.data_128)
  237. ct = cipher1.encrypt(self.data_128)
  238. tag = cipher1.digest()
  239. cipher2 = ChaCha20_Poly1305.new(key=self.key_256,
  240. nonce=self.nonce_96)
  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_256))
  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 = ChaCha20_Poly1305.new(key=self.key_256,
  259. nonce=self.nonce_96)
  260. key_mv[:3] = b'\xFF\xFF\xFF'
  261. nonce_mv[:3] = b'\xFF\xFF\xFF'
  262. cipher3.update(header_mv)
  263. header_mv[:3] = b'\xFF\xFF\xFF'
  264. pt_test = cipher3.decrypt(ct_mv)
  265. ct_mv[:3] = b'\x99\x99\x99'
  266. cipher3.verify(tag_mv)
  267. self.assertEqual(pt_test, self.data_128)
  268. import sys
  269. if sys.version[:3] == "2.6":
  270. del test_memoryview
  271. class ChaCha20Poly1305FSMTests(unittest.TestCase):
  272. key_256 = get_tag_random("key_256", 32)
  273. nonce_96 = get_tag_random("nonce_96", 12)
  274. data_128 = get_tag_random("data_128", 16)
  275. def test_valid_init_encrypt_decrypt_digest_verify(self):
  276. # No authenticated data, fixed plaintext
  277. # Verify path INIT->ENCRYPT->DIGEST
  278. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  279. nonce=self.nonce_96)
  280. ct = cipher.encrypt(self.data_128)
  281. mac = cipher.digest()
  282. # Verify path INIT->DECRYPT->VERIFY
  283. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  284. nonce=self.nonce_96)
  285. cipher.decrypt(ct)
  286. cipher.verify(mac)
  287. def test_valid_init_update_digest_verify(self):
  288. # No plaintext, fixed authenticated data
  289. # Verify path INIT->UPDATE->DIGEST
  290. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  291. nonce=self.nonce_96)
  292. cipher.update(self.data_128)
  293. mac = cipher.digest()
  294. # Verify path INIT->UPDATE->VERIFY
  295. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  296. nonce=self.nonce_96)
  297. cipher.update(self.data_128)
  298. cipher.verify(mac)
  299. def test_valid_full_path(self):
  300. # Fixed authenticated data, fixed plaintext
  301. # Verify path INIT->UPDATE->ENCRYPT->DIGEST
  302. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  303. nonce=self.nonce_96)
  304. cipher.update(self.data_128)
  305. ct = cipher.encrypt(self.data_128)
  306. mac = cipher.digest()
  307. # Verify path INIT->UPDATE->DECRYPT->VERIFY
  308. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  309. nonce=self.nonce_96)
  310. cipher.update(self.data_128)
  311. cipher.decrypt(ct)
  312. cipher.verify(mac)
  313. def test_valid_init_digest(self):
  314. # Verify path INIT->DIGEST
  315. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  316. nonce=self.nonce_96)
  317. cipher.digest()
  318. def test_valid_init_verify(self):
  319. # Verify path INIT->VERIFY
  320. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  321. nonce=self.nonce_96)
  322. mac = cipher.digest()
  323. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  324. nonce=self.nonce_96)
  325. cipher.verify(mac)
  326. def test_valid_multiple_encrypt_or_decrypt(self):
  327. for method_name in "encrypt", "decrypt":
  328. for auth_data in (None, b"333", self.data_128,
  329. self.data_128 + b"3"):
  330. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  331. nonce=self.nonce_96)
  332. if auth_data is not None:
  333. cipher.update(auth_data)
  334. method = getattr(cipher, method_name)
  335. method(self.data_128)
  336. method(self.data_128)
  337. method(self.data_128)
  338. method(self.data_128)
  339. def test_valid_multiple_digest_or_verify(self):
  340. # Multiple calls to digest
  341. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  342. nonce=self.nonce_96)
  343. cipher.update(self.data_128)
  344. first_mac = cipher.digest()
  345. for x in range(4):
  346. self.assertEqual(first_mac, cipher.digest())
  347. # Multiple calls to verify
  348. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  349. nonce=self.nonce_96)
  350. cipher.update(self.data_128)
  351. for x in range(5):
  352. cipher.verify(first_mac)
  353. def test_valid_encrypt_and_digest_decrypt_and_verify(self):
  354. # encrypt_and_digest
  355. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  356. nonce=self.nonce_96)
  357. cipher.update(self.data_128)
  358. ct, mac = cipher.encrypt_and_digest(self.data_128)
  359. # decrypt_and_verify
  360. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  361. nonce=self.nonce_96)
  362. cipher.update(self.data_128)
  363. pt = cipher.decrypt_and_verify(ct, mac)
  364. self.assertEqual(self.data_128, pt)
  365. def test_invalid_mixing_encrypt_decrypt(self):
  366. # Once per method, with or without assoc. data
  367. for method1_name, method2_name in (("encrypt", "decrypt"),
  368. ("decrypt", "encrypt")):
  369. for assoc_data_present in (True, False):
  370. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  371. nonce=self.nonce_96)
  372. if assoc_data_present:
  373. cipher.update(self.data_128)
  374. getattr(cipher, method1_name)(self.data_128)
  375. self.assertRaises(TypeError, getattr(cipher, method2_name),
  376. self.data_128)
  377. def test_invalid_encrypt_or_update_after_digest(self):
  378. for method_name in "encrypt", "update":
  379. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  380. nonce=self.nonce_96)
  381. cipher.encrypt(self.data_128)
  382. cipher.digest()
  383. self.assertRaises(TypeError, getattr(cipher, method_name),
  384. self.data_128)
  385. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  386. nonce=self.nonce_96)
  387. cipher.encrypt_and_digest(self.data_128)
  388. def test_invalid_decrypt_or_update_after_verify(self):
  389. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  390. nonce=self.nonce_96)
  391. ct = cipher.encrypt(self.data_128)
  392. mac = cipher.digest()
  393. for method_name in "decrypt", "update":
  394. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  395. nonce=self.nonce_96)
  396. cipher.decrypt(ct)
  397. cipher.verify(mac)
  398. self.assertRaises(TypeError, getattr(cipher, method_name),
  399. self.data_128)
  400. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  401. nonce=self.nonce_96)
  402. cipher.decrypt(ct)
  403. cipher.verify(mac)
  404. self.assertRaises(TypeError, getattr(cipher, method_name),
  405. self.data_128)
  406. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  407. nonce=self.nonce_96)
  408. cipher.decrypt_and_verify(ct, mac)
  409. self.assertRaises(TypeError, getattr(cipher, method_name),
  410. self.data_128)
  411. def compact(x):
  412. return unhexlify(x.replace(" ", "").replace(":", ""))
  413. class TestVectorsRFC(unittest.TestCase):
  414. """Test cases from RFC7539"""
  415. # AAD, PT, CT, MAC, KEY, NONCE
  416. test_vectors_hex = [
  417. ( '50 51 52 53 c0 c1 c2 c3 c4 c5 c6 c7',
  418. '4c 61 64 69 65 73 20 61 6e 64 20 47 65 6e 74 6c'
  419. '65 6d 65 6e 20 6f 66 20 74 68 65 20 63 6c 61 73'
  420. '73 20 6f 66 20 27 39 39 3a 20 49 66 20 49 20 63'
  421. '6f 75 6c 64 20 6f 66 66 65 72 20 79 6f 75 20 6f'
  422. '6e 6c 79 20 6f 6e 65 20 74 69 70 20 66 6f 72 20'
  423. '74 68 65 20 66 75 74 75 72 65 2c 20 73 75 6e 73'
  424. '63 72 65 65 6e 20 77 6f 75 6c 64 20 62 65 20 69'
  425. '74 2e',
  426. 'd3 1a 8d 34 64 8e 60 db 7b 86 af bc 53 ef 7e c2'
  427. 'a4 ad ed 51 29 6e 08 fe a9 e2 b5 a7 36 ee 62 d6'
  428. '3d be a4 5e 8c a9 67 12 82 fa fb 69 da 92 72 8b'
  429. '1a 71 de 0a 9e 06 0b 29 05 d6 a5 b6 7e cd 3b 36'
  430. '92 dd bd 7f 2d 77 8b 8c 98 03 ae e3 28 09 1b 58'
  431. 'fa b3 24 e4 fa d6 75 94 55 85 80 8b 48 31 d7 bc'
  432. '3f f4 de f0 8e 4b 7a 9d e5 76 d2 65 86 ce c6 4b'
  433. '61 16',
  434. '1a:e1:0b:59:4f:09:e2:6a:7e:90:2e:cb:d0:60:06:91',
  435. '80 81 82 83 84 85 86 87 88 89 8a 8b 8c 8d 8e 8f'
  436. '90 91 92 93 94 95 96 97 98 99 9a 9b 9c 9d 9e 9f',
  437. '07 00 00 00' + '40 41 42 43 44 45 46 47',
  438. ),
  439. ( 'f3 33 88 86 00 00 00 00 00 00 4e 91',
  440. '49 6e 74 65 72 6e 65 74 2d 44 72 61 66 74 73 20'
  441. '61 72 65 20 64 72 61 66 74 20 64 6f 63 75 6d 65'
  442. '6e 74 73 20 76 61 6c 69 64 20 66 6f 72 20 61 20'
  443. '6d 61 78 69 6d 75 6d 20 6f 66 20 73 69 78 20 6d'
  444. '6f 6e 74 68 73 20 61 6e 64 20 6d 61 79 20 62 65'
  445. '20 75 70 64 61 74 65 64 2c 20 72 65 70 6c 61 63'
  446. '65 64 2c 20 6f 72 20 6f 62 73 6f 6c 65 74 65 64'
  447. '20 62 79 20 6f 74 68 65 72 20 64 6f 63 75 6d 65'
  448. '6e 74 73 20 61 74 20 61 6e 79 20 74 69 6d 65 2e'
  449. '20 49 74 20 69 73 20 69 6e 61 70 70 72 6f 70 72'
  450. '69 61 74 65 20 74 6f 20 75 73 65 20 49 6e 74 65'
  451. '72 6e 65 74 2d 44 72 61 66 74 73 20 61 73 20 72'
  452. '65 66 65 72 65 6e 63 65 20 6d 61 74 65 72 69 61'
  453. '6c 20 6f 72 20 74 6f 20 63 69 74 65 20 74 68 65'
  454. '6d 20 6f 74 68 65 72 20 74 68 61 6e 20 61 73 20'
  455. '2f e2 80 9c 77 6f 72 6b 20 69 6e 20 70 72 6f 67'
  456. '72 65 73 73 2e 2f e2 80 9d',
  457. '64 a0 86 15 75 86 1a f4 60 f0 62 c7 9b e6 43 bd'
  458. '5e 80 5c fd 34 5c f3 89 f1 08 67 0a c7 6c 8c b2'
  459. '4c 6c fc 18 75 5d 43 ee a0 9e e9 4e 38 2d 26 b0'
  460. 'bd b7 b7 3c 32 1b 01 00 d4 f0 3b 7f 35 58 94 cf'
  461. '33 2f 83 0e 71 0b 97 ce 98 c8 a8 4a bd 0b 94 81'
  462. '14 ad 17 6e 00 8d 33 bd 60 f9 82 b1 ff 37 c8 55'
  463. '97 97 a0 6e f4 f0 ef 61 c1 86 32 4e 2b 35 06 38'
  464. '36 06 90 7b 6a 7c 02 b0 f9 f6 15 7b 53 c8 67 e4'
  465. 'b9 16 6c 76 7b 80 4d 46 a5 9b 52 16 cd e7 a4 e9'
  466. '90 40 c5 a4 04 33 22 5e e2 82 a1 b0 a0 6c 52 3e'
  467. 'af 45 34 d7 f8 3f a1 15 5b 00 47 71 8c bc 54 6a'
  468. '0d 07 2b 04 b3 56 4e ea 1b 42 22 73 f5 48 27 1a'
  469. '0b b2 31 60 53 fa 76 99 19 55 eb d6 31 59 43 4e'
  470. 'ce bb 4e 46 6d ae 5a 10 73 a6 72 76 27 09 7a 10'
  471. '49 e6 17 d9 1d 36 10 94 fa 68 f0 ff 77 98 71 30'
  472. '30 5b ea ba 2e da 04 df 99 7b 71 4d 6c 6f 2c 29'
  473. 'a6 ad 5c b4 02 2b 02 70 9b',
  474. 'ee ad 9d 67 89 0c bb 22 39 23 36 fe a1 85 1f 38',
  475. '1c 92 40 a5 eb 55 d3 8a f3 33 88 86 04 f6 b5 f0'
  476. '47 39 17 c1 40 2b 80 09 9d ca 5c bc 20 70 75 c0',
  477. '00 00 00 00 01 02 03 04 05 06 07 08',
  478. )
  479. ]
  480. test_vectors = [[unhexlify(x.replace(" ","").replace(":","")) for x in tv] for tv in test_vectors_hex]
  481. def runTest(self):
  482. for assoc_data, pt, ct, mac, key, nonce in self.test_vectors:
  483. # Encrypt
  484. cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce)
  485. cipher.update(assoc_data)
  486. ct2, mac2 = cipher.encrypt_and_digest(pt)
  487. self.assertEqual(ct, ct2)
  488. self.assertEqual(mac, mac2)
  489. # Decrypt
  490. cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce)
  491. cipher.update(assoc_data)
  492. pt2 = cipher.decrypt_and_verify(ct, mac)
  493. self.assertEqual(pt, pt2)
  494. class TestVectorsWycheproof(unittest.TestCase):
  495. def __init__(self, wycheproof_warnings):
  496. unittest.TestCase.__init__(self)
  497. self._wycheproof_warnings = wycheproof_warnings
  498. def setUp(self):
  499. comps = "Cryptodome.SelfTest.Cipher.test_vectors.wycheproof".split(".")
  500. with open(pycryptodome_filename(comps, "chacha20_poly1305_test.json"), "rt") as file_in:
  501. tv_tree = json.load(file_in)
  502. class TestVector(object):
  503. pass
  504. self.tv = []
  505. for group in tv_tree['testGroups']:
  506. tag_size = group['tagSize'] // 8
  507. for test in group['tests']:
  508. tv = TestVector()
  509. tv.tag_size = tag_size
  510. tv.id = test['tcId']
  511. tv.comment = test['comment']
  512. for attr in 'key', 'iv', 'aad', 'msg', 'ct', 'tag':
  513. setattr(tv, attr, unhexlify(test[attr]))
  514. tv.valid = test['result'] != "invalid"
  515. tv.warning = test['result'] == "acceptable"
  516. self.tv.append(tv)
  517. def shortDescription(self):
  518. return self._id
  519. def warn(self, tv):
  520. if tv.warning and self._wycheproof_warnings:
  521. import warnings
  522. warnings.warn("Wycheproof warning: %s (%s)" % (self._id, tv.comment))
  523. def test_encrypt(self, tv):
  524. self._id = "Wycheproof Encrypt ChaCha20-Poly1305 Test #" + str(tv.id)
  525. try:
  526. cipher = ChaCha20_Poly1305.new(key=tv.key, nonce=tv.iv)
  527. except ValueError as e:
  528. assert len(tv.iv) not in (8, 12) and "Nonce must be" in str(e)
  529. return
  530. cipher.update(tv.aad)
  531. ct, tag = cipher.encrypt_and_digest(tv.msg)
  532. if tv.valid:
  533. self.assertEqual(ct, tv.ct)
  534. self.assertEqual(tag, tv.tag)
  535. self.warn(tv)
  536. def test_decrypt(self, tv):
  537. self._id = "Wycheproof Decrypt ChaCha20-Poly1305 Test #" + str(tv.id)
  538. try:
  539. cipher = ChaCha20_Poly1305.new(key=tv.key, nonce=tv.iv)
  540. except ValueError as e:
  541. assert len(tv.iv) not in (8, 12) and "Nonce must be" in str(e)
  542. return
  543. cipher.update(tv.aad)
  544. try:
  545. pt = cipher.decrypt_and_verify(tv.ct, tv.tag)
  546. except ValueError:
  547. assert not tv.valid
  548. else:
  549. assert tv.valid
  550. self.assertEqual(pt, tv.msg)
  551. self.warn(tv)
  552. def test_corrupt_decrypt(self, tv):
  553. self._id = "Wycheproof Corrupt Decrypt ChaCha20-Poly1305 Test #" + str(tv.id)
  554. if len(tv.iv) == 0 or len(tv.ct) < 1:
  555. return
  556. cipher = ChaCha20_Poly1305.new(key=tv.key, nonce=tv.iv)
  557. cipher.update(tv.aad)
  558. ct_corrupt = strxor(tv.ct, b"\x00" * (len(tv.ct) - 1) + b"\x01")
  559. self.assertRaises(ValueError, cipher.decrypt_and_verify, ct_corrupt, tv.tag)
  560. def runTest(self):
  561. for tv in self.tv:
  562. self.test_encrypt(tv)
  563. self.test_decrypt(tv)
  564. self.test_corrupt_decrypt(tv)
  565. class TestOutput(unittest.TestCase):
  566. def runTest(self):
  567. # Encrypt/Decrypt data and test output parameter
  568. key = b'4' * 32
  569. nonce = b'5' * 12
  570. cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce)
  571. pt = b'5' * 16
  572. ct = cipher.encrypt(pt)
  573. output = bytearray(16)
  574. cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce)
  575. res = cipher.encrypt(pt, output=output)
  576. self.assertEqual(ct, output)
  577. self.assertEqual(res, None)
  578. cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce)
  579. res = cipher.decrypt(ct, output=output)
  580. self.assertEqual(pt, output)
  581. self.assertEqual(res, None)
  582. import sys
  583. if sys.version[:3] != '2.6':
  584. output = memoryview(bytearray(16))
  585. cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce)
  586. cipher.encrypt(pt, output=output)
  587. self.assertEqual(ct, output)
  588. cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce)
  589. cipher.decrypt(ct, output=output)
  590. self.assertEqual(pt, output)
  591. cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce)
  592. self.assertRaises(TypeError, cipher.encrypt, pt, output=b'0'*16)
  593. cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce)
  594. self.assertRaises(TypeError, cipher.decrypt, ct, output=b'0'*16)
  595. shorter_output = bytearray(7)
  596. cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce)
  597. self.assertRaises(ValueError, cipher.encrypt, pt, output=shorter_output)
  598. cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce)
  599. self.assertRaises(ValueError, cipher.decrypt, ct, output=shorter_output)
  600. def get_tests(config={}):
  601. wycheproof_warnings = config.get('wycheproof_warnings')
  602. tests = []
  603. tests += list_test_cases(ChaCha20Poly1305Tests)
  604. tests += list_test_cases(ChaCha20Poly1305FSMTests)
  605. tests += [TestVectorsRFC()]
  606. tests += [TestVectorsWycheproof(wycheproof_warnings)]
  607. tests += [TestOutput()]
  608. return tests
  609. if __name__ == '__main__':
  610. def suite():
  611. unittest.TestSuite(get_tests())
  612. unittest.main(defaultTest='suite')