test_ChaCha20_Poly1305.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  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 tls.Crypto.SelfTest.st_common import list_test_cases
  34. from tls.Crypto.Util.py3compat import tobytes, _memoryview
  35. from tls.Crypto.Cipher import ChaCha20_Poly1305
  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 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 tls.Crypto.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 XChaCha20Poly1305Tests(unittest.TestCase):
  272. def test_encrypt(self):
  273. # From https://tools.ietf.org/html/draft-arciszewski-xchacha-03
  274. # Section A.3.1
  275. pt = b"""
  276. 4c616469657320616e642047656e746c656d656e206f662074686520636c6173
  277. 73206f66202739393a204966204920636f756c64206f6666657220796f75206f
  278. 6e6c79206f6e652074697020666f7220746865206675747572652c2073756e73
  279. 637265656e20776f756c642062652069742e"""
  280. pt = unhexlify(pt.replace(b"\n", b"").replace(b" ", b""))
  281. aad = unhexlify(b"50515253c0c1c2c3c4c5c6c7")
  282. key = unhexlify(b"808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f")
  283. iv = unhexlify(b"404142434445464748494a4b4c4d4e4f5051525354555657")
  284. ct = b"""
  285. bd6d179d3e83d43b9576579493c0e939572a1700252bfaccbed2902c21396cbb
  286. 731c7f1b0b4aa6440bf3a82f4eda7e39ae64c6708c54c216cb96b72e1213b452
  287. 2f8c9ba40db5d945b11b69b982c1bb9e3f3fac2bc369488f76b2383565d3fff9
  288. 21f9664c97637da9768812f615c68b13b52e"""
  289. ct = unhexlify(ct.replace(b"\n", b"").replace(b" ", b""))
  290. tag = unhexlify(b"c0875924c1c7987947deafd8780acf49")
  291. cipher = ChaCha20_Poly1305.new(key=key, nonce=iv)
  292. cipher.update(aad)
  293. ct_test, tag_test = cipher.encrypt_and_digest(pt)
  294. self.assertEqual(ct, ct_test)
  295. self.assertEqual(tag, tag_test)
  296. cipher = ChaCha20_Poly1305.new(key=key, nonce=iv)
  297. cipher.update(aad)
  298. cipher.decrypt_and_verify(ct, tag)
  299. class ChaCha20Poly1305FSMTests(unittest.TestCase):
  300. key_256 = get_tag_random("key_256", 32)
  301. nonce_96 = get_tag_random("nonce_96", 12)
  302. data_128 = get_tag_random("data_128", 16)
  303. def test_valid_init_encrypt_decrypt_digest_verify(self):
  304. # No authenticated data, fixed plaintext
  305. # Verify path INIT->ENCRYPT->DIGEST
  306. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  307. nonce=self.nonce_96)
  308. ct = cipher.encrypt(self.data_128)
  309. mac = cipher.digest()
  310. # Verify path INIT->DECRYPT->VERIFY
  311. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  312. nonce=self.nonce_96)
  313. cipher.decrypt(ct)
  314. cipher.verify(mac)
  315. def test_valid_init_update_digest_verify(self):
  316. # No plaintext, fixed authenticated data
  317. # Verify path INIT->UPDATE->DIGEST
  318. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  319. nonce=self.nonce_96)
  320. cipher.update(self.data_128)
  321. mac = cipher.digest()
  322. # Verify path INIT->UPDATE->VERIFY
  323. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  324. nonce=self.nonce_96)
  325. cipher.update(self.data_128)
  326. cipher.verify(mac)
  327. def test_valid_full_path(self):
  328. # Fixed authenticated data, fixed plaintext
  329. # Verify path INIT->UPDATE->ENCRYPT->DIGEST
  330. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  331. nonce=self.nonce_96)
  332. cipher.update(self.data_128)
  333. ct = cipher.encrypt(self.data_128)
  334. mac = cipher.digest()
  335. # Verify path INIT->UPDATE->DECRYPT->VERIFY
  336. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  337. nonce=self.nonce_96)
  338. cipher.update(self.data_128)
  339. cipher.decrypt(ct)
  340. cipher.verify(mac)
  341. def test_valid_init_digest(self):
  342. # Verify path INIT->DIGEST
  343. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  344. nonce=self.nonce_96)
  345. cipher.digest()
  346. def test_valid_init_verify(self):
  347. # Verify path INIT->VERIFY
  348. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  349. nonce=self.nonce_96)
  350. mac = cipher.digest()
  351. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  352. nonce=self.nonce_96)
  353. cipher.verify(mac)
  354. def test_valid_multiple_encrypt_or_decrypt(self):
  355. for method_name in "encrypt", "decrypt":
  356. for auth_data in (None, b"333", self.data_128,
  357. self.data_128 + b"3"):
  358. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  359. nonce=self.nonce_96)
  360. if auth_data is not None:
  361. cipher.update(auth_data)
  362. method = getattr(cipher, method_name)
  363. method(self.data_128)
  364. method(self.data_128)
  365. method(self.data_128)
  366. method(self.data_128)
  367. def test_valid_multiple_digest_or_verify(self):
  368. # Multiple calls to digest
  369. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  370. nonce=self.nonce_96)
  371. cipher.update(self.data_128)
  372. first_mac = cipher.digest()
  373. for x in range(4):
  374. self.assertEqual(first_mac, cipher.digest())
  375. # Multiple calls to verify
  376. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  377. nonce=self.nonce_96)
  378. cipher.update(self.data_128)
  379. for x in range(5):
  380. cipher.verify(first_mac)
  381. def test_valid_encrypt_and_digest_decrypt_and_verify(self):
  382. # encrypt_and_digest
  383. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  384. nonce=self.nonce_96)
  385. cipher.update(self.data_128)
  386. ct, mac = cipher.encrypt_and_digest(self.data_128)
  387. # decrypt_and_verify
  388. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  389. nonce=self.nonce_96)
  390. cipher.update(self.data_128)
  391. pt = cipher.decrypt_and_verify(ct, mac)
  392. self.assertEqual(self.data_128, pt)
  393. def test_invalid_mixing_encrypt_decrypt(self):
  394. # Once per method, with or without assoc. data
  395. for method1_name, method2_name in (("encrypt", "decrypt"),
  396. ("decrypt", "encrypt")):
  397. for assoc_data_present in (True, False):
  398. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  399. nonce=self.nonce_96)
  400. if assoc_data_present:
  401. cipher.update(self.data_128)
  402. getattr(cipher, method1_name)(self.data_128)
  403. self.assertRaises(TypeError, getattr(cipher, method2_name),
  404. self.data_128)
  405. def test_invalid_encrypt_or_update_after_digest(self):
  406. for method_name in "encrypt", "update":
  407. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  408. nonce=self.nonce_96)
  409. cipher.encrypt(self.data_128)
  410. cipher.digest()
  411. self.assertRaises(TypeError, getattr(cipher, method_name),
  412. self.data_128)
  413. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  414. nonce=self.nonce_96)
  415. cipher.encrypt_and_digest(self.data_128)
  416. def test_invalid_decrypt_or_update_after_verify(self):
  417. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  418. nonce=self.nonce_96)
  419. ct = cipher.encrypt(self.data_128)
  420. mac = cipher.digest()
  421. for method_name in "decrypt", "update":
  422. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  423. nonce=self.nonce_96)
  424. cipher.decrypt(ct)
  425. cipher.verify(mac)
  426. self.assertRaises(TypeError, getattr(cipher, method_name),
  427. self.data_128)
  428. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  429. nonce=self.nonce_96)
  430. cipher.decrypt(ct)
  431. cipher.verify(mac)
  432. self.assertRaises(TypeError, getattr(cipher, method_name),
  433. self.data_128)
  434. cipher = ChaCha20_Poly1305.new(key=self.key_256,
  435. nonce=self.nonce_96)
  436. cipher.decrypt_and_verify(ct, mac)
  437. self.assertRaises(TypeError, getattr(cipher, method_name),
  438. self.data_128)
  439. def compact(x):
  440. return unhexlify(x.replace(" ", "").replace(":", ""))
  441. class TestVectorsRFC(unittest.TestCase):
  442. """Test cases from RFC7539"""
  443. # AAD, PT, CT, MAC, KEY, NONCE
  444. test_vectors_hex = [
  445. ( '50 51 52 53 c0 c1 c2 c3 c4 c5 c6 c7',
  446. '4c 61 64 69 65 73 20 61 6e 64 20 47 65 6e 74 6c'
  447. '65 6d 65 6e 20 6f 66 20 74 68 65 20 63 6c 61 73'
  448. '73 20 6f 66 20 27 39 39 3a 20 49 66 20 49 20 63'
  449. '6f 75 6c 64 20 6f 66 66 65 72 20 79 6f 75 20 6f'
  450. '6e 6c 79 20 6f 6e 65 20 74 69 70 20 66 6f 72 20'
  451. '74 68 65 20 66 75 74 75 72 65 2c 20 73 75 6e 73'
  452. '63 72 65 65 6e 20 77 6f 75 6c 64 20 62 65 20 69'
  453. '74 2e',
  454. 'd3 1a 8d 34 64 8e 60 db 7b 86 af bc 53 ef 7e c2'
  455. 'a4 ad ed 51 29 6e 08 fe a9 e2 b5 a7 36 ee 62 d6'
  456. '3d be a4 5e 8c a9 67 12 82 fa fb 69 da 92 72 8b'
  457. '1a 71 de 0a 9e 06 0b 29 05 d6 a5 b6 7e cd 3b 36'
  458. '92 dd bd 7f 2d 77 8b 8c 98 03 ae e3 28 09 1b 58'
  459. 'fa b3 24 e4 fa d6 75 94 55 85 80 8b 48 31 d7 bc'
  460. '3f f4 de f0 8e 4b 7a 9d e5 76 d2 65 86 ce c6 4b'
  461. '61 16',
  462. '1a:e1:0b:59:4f:09:e2:6a:7e:90:2e:cb:d0:60:06:91',
  463. '80 81 82 83 84 85 86 87 88 89 8a 8b 8c 8d 8e 8f'
  464. '90 91 92 93 94 95 96 97 98 99 9a 9b 9c 9d 9e 9f',
  465. '07 00 00 00' + '40 41 42 43 44 45 46 47',
  466. ),
  467. ( 'f3 33 88 86 00 00 00 00 00 00 4e 91',
  468. '49 6e 74 65 72 6e 65 74 2d 44 72 61 66 74 73 20'
  469. '61 72 65 20 64 72 61 66 74 20 64 6f 63 75 6d 65'
  470. '6e 74 73 20 76 61 6c 69 64 20 66 6f 72 20 61 20'
  471. '6d 61 78 69 6d 75 6d 20 6f 66 20 73 69 78 20 6d'
  472. '6f 6e 74 68 73 20 61 6e 64 20 6d 61 79 20 62 65'
  473. '20 75 70 64 61 74 65 64 2c 20 72 65 70 6c 61 63'
  474. '65 64 2c 20 6f 72 20 6f 62 73 6f 6c 65 74 65 64'
  475. '20 62 79 20 6f 74 68 65 72 20 64 6f 63 75 6d 65'
  476. '6e 74 73 20 61 74 20 61 6e 79 20 74 69 6d 65 2e'
  477. '20 49 74 20 69 73 20 69 6e 61 70 70 72 6f 70 72'
  478. '69 61 74 65 20 74 6f 20 75 73 65 20 49 6e 74 65'
  479. '72 6e 65 74 2d 44 72 61 66 74 73 20 61 73 20 72'
  480. '65 66 65 72 65 6e 63 65 20 6d 61 74 65 72 69 61'
  481. '6c 20 6f 72 20 74 6f 20 63 69 74 65 20 74 68 65'
  482. '6d 20 6f 74 68 65 72 20 74 68 61 6e 20 61 73 20'
  483. '2f e2 80 9c 77 6f 72 6b 20 69 6e 20 70 72 6f 67'
  484. '72 65 73 73 2e 2f e2 80 9d',
  485. '64 a0 86 15 75 86 1a f4 60 f0 62 c7 9b e6 43 bd'
  486. '5e 80 5c fd 34 5c f3 89 f1 08 67 0a c7 6c 8c b2'
  487. '4c 6c fc 18 75 5d 43 ee a0 9e e9 4e 38 2d 26 b0'
  488. 'bd b7 b7 3c 32 1b 01 00 d4 f0 3b 7f 35 58 94 cf'
  489. '33 2f 83 0e 71 0b 97 ce 98 c8 a8 4a bd 0b 94 81'
  490. '14 ad 17 6e 00 8d 33 bd 60 f9 82 b1 ff 37 c8 55'
  491. '97 97 a0 6e f4 f0 ef 61 c1 86 32 4e 2b 35 06 38'
  492. '36 06 90 7b 6a 7c 02 b0 f9 f6 15 7b 53 c8 67 e4'
  493. 'b9 16 6c 76 7b 80 4d 46 a5 9b 52 16 cd e7 a4 e9'
  494. '90 40 c5 a4 04 33 22 5e e2 82 a1 b0 a0 6c 52 3e'
  495. 'af 45 34 d7 f8 3f a1 15 5b 00 47 71 8c bc 54 6a'
  496. '0d 07 2b 04 b3 56 4e ea 1b 42 22 73 f5 48 27 1a'
  497. '0b b2 31 60 53 fa 76 99 19 55 eb d6 31 59 43 4e'
  498. 'ce bb 4e 46 6d ae 5a 10 73 a6 72 76 27 09 7a 10'
  499. '49 e6 17 d9 1d 36 10 94 fa 68 f0 ff 77 98 71 30'
  500. '30 5b ea ba 2e da 04 df 99 7b 71 4d 6c 6f 2c 29'
  501. 'a6 ad 5c b4 02 2b 02 70 9b',
  502. 'ee ad 9d 67 89 0c bb 22 39 23 36 fe a1 85 1f 38',
  503. '1c 92 40 a5 eb 55 d3 8a f3 33 88 86 04 f6 b5 f0'
  504. '47 39 17 c1 40 2b 80 09 9d ca 5c bc 20 70 75 c0',
  505. '00 00 00 00 01 02 03 04 05 06 07 08',
  506. )
  507. ]
  508. test_vectors = [[unhexlify(x.replace(" ","").replace(":","")) for x in tv] for tv in test_vectors_hex]
  509. def runTest(self):
  510. for assoc_data, pt, ct, mac, key, nonce in self.test_vectors:
  511. # Encrypt
  512. cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce)
  513. cipher.update(assoc_data)
  514. ct2, mac2 = cipher.encrypt_and_digest(pt)
  515. self.assertEqual(ct, ct2)
  516. self.assertEqual(mac, mac2)
  517. # Decrypt
  518. cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce)
  519. cipher.update(assoc_data)
  520. pt2 = cipher.decrypt_and_verify(ct, mac)
  521. self.assertEqual(pt, pt2)
  522. class TestVectorsWycheproof(unittest.TestCase):
  523. def __init__(self, wycheproof_warnings):
  524. unittest.TestCase.__init__(self)
  525. self._wycheproof_warnings = wycheproof_warnings
  526. self._id = "None"
  527. def load_tests(self, filename):
  528. comps = "Crypto.SelfTest.Cipher.test_vectors.wycheproof".split(".")
  529. with open(pycryptodome_filename(comps, filename), "rt") as file_in:
  530. tv_tree = json.load(file_in)
  531. class TestVector(object):
  532. pass
  533. result = []
  534. for group in tv_tree['testGroups']:
  535. tag_size = group['tagSize'] // 8
  536. for test in group['tests']:
  537. tv = TestVector()
  538. tv.tag_size = tag_size
  539. tv.id = test['tcId']
  540. tv.comment = test['comment']
  541. for attr in 'key', 'iv', 'aad', 'msg', 'ct', 'tag':
  542. setattr(tv, attr, unhexlify(test[attr]))
  543. tv.valid = test['result'] != "invalid"
  544. tv.warning = test['result'] == "acceptable"
  545. tv.algo = tv_tree['algorithm']
  546. result.append(tv)
  547. return result
  548. def setUp(self):
  549. self.tv = []
  550. self.tv.extend(self.load_tests("chacha20_poly1305_test.json"))
  551. self.tv.extend(self.load_tests("xchacha20_poly1305_test.json"))
  552. def shortDescription(self):
  553. return self._id
  554. def warn(self, tv):
  555. if tv.warning and self._wycheproof_warnings:
  556. import warnings
  557. warnings.warn("Wycheproof warning: %s (%s)" % (self._id, tv.comment))
  558. def test_encrypt(self, tv):
  559. self._id = "Wycheproof Encrypt %s Test #%s" % (tv.algo, tv.id)
  560. try:
  561. cipher = ChaCha20_Poly1305.new(key=tv.key, nonce=tv.iv)
  562. except ValueError as e:
  563. assert len(tv.iv) not in (8, 12) and "Nonce must be" in str(e)
  564. return
  565. cipher.update(tv.aad)
  566. ct, tag = cipher.encrypt_and_digest(tv.msg)
  567. if tv.valid:
  568. self.assertEqual(ct, tv.ct)
  569. self.assertEqual(tag, tv.tag)
  570. self.warn(tv)
  571. def test_decrypt(self, tv):
  572. self._id = "Wycheproof Decrypt %s Test #%s" % (tv.algo, tv.id)
  573. try:
  574. cipher = ChaCha20_Poly1305.new(key=tv.key, nonce=tv.iv)
  575. except ValueError as e:
  576. assert len(tv.iv) not in (8, 12) and "Nonce must be" in str(e)
  577. return
  578. cipher.update(tv.aad)
  579. try:
  580. pt = cipher.decrypt_and_verify(tv.ct, tv.tag)
  581. except ValueError:
  582. assert not tv.valid
  583. else:
  584. assert tv.valid
  585. self.assertEqual(pt, tv.msg)
  586. self.warn(tv)
  587. def test_corrupt_decrypt(self, tv):
  588. self._id = "Wycheproof Corrupt Decrypt ChaCha20-Poly1305 Test #" + str(tv.id)
  589. if len(tv.iv) == 0 or len(tv.ct) < 1:
  590. return
  591. cipher = ChaCha20_Poly1305.new(key=tv.key, nonce=tv.iv)
  592. cipher.update(tv.aad)
  593. ct_corrupt = strxor(tv.ct, b"\x00" * (len(tv.ct) - 1) + b"\x01")
  594. self.assertRaises(ValueError, cipher.decrypt_and_verify, ct_corrupt, tv.tag)
  595. def runTest(self):
  596. for tv in self.tv:
  597. self.test_encrypt(tv)
  598. self.test_decrypt(tv)
  599. self.test_corrupt_decrypt(tv)
  600. class TestOutput(unittest.TestCase):
  601. def runTest(self):
  602. # Encrypt/Decrypt data and test output parameter
  603. key = b'4' * 32
  604. nonce = b'5' * 12
  605. cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce)
  606. pt = b'5' * 16
  607. ct = cipher.encrypt(pt)
  608. output = bytearray(16)
  609. cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce)
  610. res = cipher.encrypt(pt, output=output)
  611. self.assertEqual(ct, output)
  612. self.assertEqual(res, None)
  613. cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce)
  614. res = cipher.decrypt(ct, output=output)
  615. self.assertEqual(pt, output)
  616. self.assertEqual(res, None)
  617. import sys
  618. if sys.version[:3] != '2.6':
  619. output = memoryview(bytearray(16))
  620. cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce)
  621. cipher.encrypt(pt, output=output)
  622. self.assertEqual(ct, output)
  623. cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce)
  624. cipher.decrypt(ct, output=output)
  625. self.assertEqual(pt, output)
  626. cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce)
  627. self.assertRaises(TypeError, cipher.encrypt, pt, output=b'0'*16)
  628. cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce)
  629. self.assertRaises(TypeError, cipher.decrypt, ct, output=b'0'*16)
  630. shorter_output = bytearray(7)
  631. cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce)
  632. self.assertRaises(ValueError, cipher.encrypt, pt, output=shorter_output)
  633. cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce)
  634. self.assertRaises(ValueError, cipher.decrypt, ct, output=shorter_output)
  635. def get_tests(config={}):
  636. wycheproof_warnings = config.get('wycheproof_warnings')
  637. tests = []
  638. tests += list_test_cases(ChaCha20Poly1305Tests)
  639. tests += list_test_cases(XChaCha20Poly1305Tests)
  640. tests += list_test_cases(ChaCha20Poly1305FSMTests)
  641. tests += [TestVectorsRFC()]
  642. tests += [TestVectorsWycheproof(wycheproof_warnings)]
  643. tests += [TestOutput()]
  644. return tests
  645. if __name__ == '__main__':
  646. def suite():
  647. unittest.TestSuite(get_tests())
  648. unittest.main(defaultTest='suite')