test_ChaCha20_Poly1305.py 30 KB

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