test_GCM.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970
  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. from __future__ import print_function
  31. import json
  32. import unittest
  33. from binascii import unhexlify
  34. from tls.Crypto.SelfTest.st_common import list_test_cases
  35. from tls.Crypto.SelfTest.loader import load_tests
  36. from tls.Crypto.Util.py3compat import tobytes, bchr, _memoryview
  37. from tls.Crypto.Cipher import AES
  38. from tls.Crypto.Hash import SHAKE128, SHA256
  39. from tls.Crypto.Util._file_system import pycryptodome_filename
  40. from tls.Crypto.Util.strxor import strxor
  41. def get_tag_random(tag, length):
  42. return SHAKE128.new(data=tobytes(tag)).read(length)
  43. class GcmTests(unittest.TestCase):
  44. key_128 = get_tag_random("key_128", 16)
  45. nonce_96 = get_tag_random("nonce_128", 12)
  46. data_128 = get_tag_random("data_128", 16)
  47. def test_loopback_128(self):
  48. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  49. pt = get_tag_random("plaintext", 16 * 100)
  50. ct = cipher.encrypt(pt)
  51. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  52. pt2 = cipher.decrypt(ct)
  53. self.assertEqual(pt, pt2)
  54. def test_nonce(self):
  55. # Nonce is optional (a random one will be created)
  56. AES.new(self.key_128, AES.MODE_GCM)
  57. cipher = AES.new(self.key_128, AES.MODE_GCM, self.nonce_96)
  58. ct = cipher.encrypt(self.data_128)
  59. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  60. self.assertEquals(ct, cipher.encrypt(self.data_128))
  61. def test_nonce_must_be_bytes(self):
  62. self.assertRaises(TypeError, AES.new, self.key_128, AES.MODE_GCM,
  63. nonce=u'test12345678')
  64. def test_nonce_length(self):
  65. # nonce can be of any length (but not empty)
  66. self.assertRaises(ValueError, AES.new, self.key_128, AES.MODE_GCM,
  67. nonce=b"")
  68. for x in range(1, 128):
  69. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=bchr(1) * x)
  70. cipher.encrypt(bchr(1))
  71. def test_block_size_128(self):
  72. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  73. self.assertEqual(cipher.block_size, AES.block_size)
  74. def test_nonce_attribute(self):
  75. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  76. self.assertEqual(cipher.nonce, self.nonce_96)
  77. # By default, a 15 bytes long nonce is randomly generated
  78. nonce1 = AES.new(self.key_128, AES.MODE_GCM).nonce
  79. nonce2 = AES.new(self.key_128, AES.MODE_GCM).nonce
  80. self.assertEqual(len(nonce1), 16)
  81. self.assertNotEqual(nonce1, nonce2)
  82. def test_unknown_parameters(self):
  83. self.assertRaises(TypeError, AES.new, self.key_128, AES.MODE_GCM,
  84. self.nonce_96, 7)
  85. self.assertRaises(TypeError, AES.new, self.key_128, AES.MODE_GCM,
  86. nonce=self.nonce_96, unknown=7)
  87. # But some are only known by the base cipher
  88. # (e.g. use_aesni consumed by the AES module)
  89. AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96,
  90. use_aesni=False)
  91. def test_null_encryption_decryption(self):
  92. for func in "encrypt", "decrypt":
  93. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  94. result = getattr(cipher, func)(b"")
  95. self.assertEqual(result, b"")
  96. def test_either_encrypt_or_decrypt(self):
  97. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  98. cipher.encrypt(b"")
  99. self.assertRaises(TypeError, cipher.decrypt, b"")
  100. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  101. cipher.decrypt(b"")
  102. self.assertRaises(TypeError, cipher.encrypt, b"")
  103. def test_data_must_be_bytes(self):
  104. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  105. self.assertRaises(TypeError, cipher.encrypt, u'test1234567890-*')
  106. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  107. self.assertRaises(TypeError, cipher.decrypt, u'test1234567890-*')
  108. def test_mac_len(self):
  109. # Invalid MAC length
  110. self.assertRaises(ValueError, AES.new, self.key_128, AES.MODE_GCM,
  111. nonce=self.nonce_96, mac_len=3)
  112. self.assertRaises(ValueError, AES.new, self.key_128, AES.MODE_GCM,
  113. nonce=self.nonce_96, mac_len=16+1)
  114. # Valid MAC length
  115. for mac_len in range(5, 16 + 1):
  116. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96,
  117. mac_len=mac_len)
  118. _, mac = cipher.encrypt_and_digest(self.data_128)
  119. self.assertEqual(len(mac), mac_len)
  120. # Default MAC length
  121. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  122. _, mac = cipher.encrypt_and_digest(self.data_128)
  123. self.assertEqual(len(mac), 16)
  124. def test_invalid_mac(self):
  125. from tls.Crypto.Util.strxor import strxor_c
  126. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  127. ct, mac = cipher.encrypt_and_digest(self.data_128)
  128. invalid_mac = strxor_c(mac, 0x01)
  129. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  130. self.assertRaises(ValueError, cipher.decrypt_and_verify, ct,
  131. invalid_mac)
  132. def test_hex_mac(self):
  133. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  134. mac_hex = cipher.hexdigest()
  135. self.assertEqual(cipher.digest(), unhexlify(mac_hex))
  136. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  137. cipher.hexverify(mac_hex)
  138. def test_message_chunks(self):
  139. # Validate that both associated data and plaintext/ciphertext
  140. # can be broken up in chunks of arbitrary length
  141. auth_data = get_tag_random("authenticated data", 127)
  142. plaintext = get_tag_random("plaintext", 127)
  143. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  144. cipher.update(auth_data)
  145. ciphertext, ref_mac = cipher.encrypt_and_digest(plaintext)
  146. def break_up(data, chunk_length):
  147. return [data[i:i+chunk_length] for i in range(0, len(data),
  148. chunk_length)]
  149. # Encryption
  150. for chunk_length in 1, 2, 3, 7, 10, 13, 16, 40, 80, 128:
  151. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  152. for chunk in break_up(auth_data, chunk_length):
  153. cipher.update(chunk)
  154. pt2 = b""
  155. for chunk in break_up(ciphertext, chunk_length):
  156. pt2 += cipher.decrypt(chunk)
  157. self.assertEqual(plaintext, pt2)
  158. cipher.verify(ref_mac)
  159. # Decryption
  160. for chunk_length in 1, 2, 3, 7, 10, 13, 16, 40, 80, 128:
  161. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  162. for chunk in break_up(auth_data, chunk_length):
  163. cipher.update(chunk)
  164. ct2 = b""
  165. for chunk in break_up(plaintext, chunk_length):
  166. ct2 += cipher.encrypt(chunk)
  167. self.assertEqual(ciphertext, ct2)
  168. self.assertEquals(cipher.digest(), ref_mac)
  169. def test_bytearray(self):
  170. # Encrypt
  171. key_ba = bytearray(self.key_128)
  172. nonce_ba = bytearray(self.nonce_96)
  173. header_ba = bytearray(self.data_128)
  174. data_ba = bytearray(self.data_128)
  175. cipher1 = AES.new(self.key_128,
  176. AES.MODE_GCM,
  177. nonce=self.nonce_96)
  178. cipher1.update(self.data_128)
  179. ct = cipher1.encrypt(self.data_128)
  180. tag = cipher1.digest()
  181. cipher2 = AES.new(key_ba,
  182. AES.MODE_GCM,
  183. nonce=nonce_ba)
  184. key_ba[:3] = b"\xFF\xFF\xFF"
  185. nonce_ba[:3] = b"\xFF\xFF\xFF"
  186. cipher2.update(header_ba)
  187. header_ba[:3] = b"\xFF\xFF\xFF"
  188. ct_test = cipher2.encrypt(data_ba)
  189. data_ba[:3] = b"\xFF\xFF\xFF"
  190. tag_test = cipher2.digest()
  191. self.assertEqual(ct, ct_test)
  192. self.assertEqual(tag, tag_test)
  193. self.assertEqual(cipher1.nonce, cipher2.nonce)
  194. # Decrypt
  195. key_ba = bytearray(self.key_128)
  196. nonce_ba = bytearray(self.nonce_96)
  197. header_ba = bytearray(self.data_128)
  198. del data_ba
  199. cipher4 = AES.new(key_ba,
  200. AES.MODE_GCM,
  201. nonce=nonce_ba)
  202. key_ba[:3] = b"\xFF\xFF\xFF"
  203. nonce_ba[:3] = b"\xFF\xFF\xFF"
  204. cipher4.update(header_ba)
  205. header_ba[:3] = b"\xFF\xFF\xFF"
  206. pt_test = cipher4.decrypt_and_verify(bytearray(ct_test), bytearray(tag_test))
  207. self.assertEqual(self.data_128, pt_test)
  208. def test_memoryview(self):
  209. # Encrypt
  210. key_mv = memoryview(bytearray(self.key_128))
  211. nonce_mv = memoryview(bytearray(self.nonce_96))
  212. header_mv = memoryview(bytearray(self.data_128))
  213. data_mv = memoryview(bytearray(self.data_128))
  214. cipher1 = AES.new(self.key_128,
  215. AES.MODE_GCM,
  216. nonce=self.nonce_96)
  217. cipher1.update(self.data_128)
  218. ct = cipher1.encrypt(self.data_128)
  219. tag = cipher1.digest()
  220. cipher2 = AES.new(key_mv,
  221. AES.MODE_GCM,
  222. nonce=nonce_mv)
  223. key_mv[:3] = b"\xFF\xFF\xFF"
  224. nonce_mv[:3] = b"\xFF\xFF\xFF"
  225. cipher2.update(header_mv)
  226. header_mv[:3] = b"\xFF\xFF\xFF"
  227. ct_test = cipher2.encrypt(data_mv)
  228. data_mv[:3] = b"\xFF\xFF\xFF"
  229. tag_test = cipher2.digest()
  230. self.assertEqual(ct, ct_test)
  231. self.assertEqual(tag, tag_test)
  232. self.assertEqual(cipher1.nonce, cipher2.nonce)
  233. # Decrypt
  234. key_mv = memoryview(bytearray(self.key_128))
  235. nonce_mv = memoryview(bytearray(self.nonce_96))
  236. header_mv = memoryview(bytearray(self.data_128))
  237. del data_mv
  238. cipher4 = AES.new(key_mv,
  239. AES.MODE_GCM,
  240. nonce=nonce_mv)
  241. key_mv[:3] = b"\xFF\xFF\xFF"
  242. nonce_mv[:3] = b"\xFF\xFF\xFF"
  243. cipher4.update(header_mv)
  244. header_mv[:3] = b"\xFF\xFF\xFF"
  245. pt_test = cipher4.decrypt_and_verify(memoryview(ct_test), memoryview(tag_test))
  246. self.assertEqual(self.data_128, pt_test)
  247. def test_output_param(self):
  248. pt = b'5' * 16
  249. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  250. ct = cipher.encrypt(pt)
  251. tag = cipher.digest()
  252. output = bytearray(16)
  253. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  254. res = cipher.encrypt(pt, output=output)
  255. self.assertEqual(ct, output)
  256. self.assertEqual(res, None)
  257. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  258. res = cipher.decrypt(ct, output=output)
  259. self.assertEqual(pt, output)
  260. self.assertEqual(res, None)
  261. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  262. res, tag_out = cipher.encrypt_and_digest(pt, output=output)
  263. self.assertEqual(ct, output)
  264. self.assertEqual(res, None)
  265. self.assertEqual(tag, tag_out)
  266. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  267. res = cipher.decrypt_and_verify(ct, tag, output=output)
  268. self.assertEqual(pt, output)
  269. self.assertEqual(res, None)
  270. def test_output_param_memoryview(self):
  271. pt = b'5' * 16
  272. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  273. ct = cipher.encrypt(pt)
  274. output = memoryview(bytearray(16))
  275. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  276. cipher.encrypt(pt, output=output)
  277. self.assertEqual(ct, output)
  278. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  279. cipher.decrypt(ct, output=output)
  280. self.assertEqual(pt, output)
  281. def test_output_param_neg(self):
  282. pt = b'5' * 16
  283. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  284. ct = cipher.encrypt(pt)
  285. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  286. self.assertRaises(TypeError, cipher.encrypt, pt, output=b'0'*16)
  287. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  288. self.assertRaises(TypeError, cipher.decrypt, ct, output=b'0'*16)
  289. shorter_output = bytearray(15)
  290. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  291. self.assertRaises(ValueError, cipher.encrypt, pt, output=shorter_output)
  292. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  293. self.assertRaises(ValueError, cipher.decrypt, ct, output=shorter_output)
  294. import sys
  295. if sys.version[:3] == "2.6":
  296. del test_memoryview
  297. del test_output_param_memoryview
  298. class GcmFSMTests(unittest.TestCase):
  299. key_128 = get_tag_random("key_128", 16)
  300. nonce_96 = get_tag_random("nonce_128", 12)
  301. data_128 = get_tag_random("data_128", 16)
  302. def test_valid_init_encrypt_decrypt_digest_verify(self):
  303. # No authenticated data, fixed plaintext
  304. # Verify path INIT->ENCRYPT->DIGEST
  305. cipher = AES.new(self.key_128, AES.MODE_GCM,
  306. nonce=self.nonce_96)
  307. ct = cipher.encrypt(self.data_128)
  308. mac = cipher.digest()
  309. # Verify path INIT->DECRYPT->VERIFY
  310. cipher = AES.new(self.key_128, AES.MODE_GCM,
  311. nonce=self.nonce_96)
  312. cipher.decrypt(ct)
  313. cipher.verify(mac)
  314. def test_valid_init_update_digest_verify(self):
  315. # No plaintext, fixed authenticated data
  316. # Verify path INIT->UPDATE->DIGEST
  317. cipher = AES.new(self.key_128, AES.MODE_GCM,
  318. nonce=self.nonce_96)
  319. cipher.update(self.data_128)
  320. mac = cipher.digest()
  321. # Verify path INIT->UPDATE->VERIFY
  322. cipher = AES.new(self.key_128, AES.MODE_GCM,
  323. nonce=self.nonce_96)
  324. cipher.update(self.data_128)
  325. cipher.verify(mac)
  326. def test_valid_full_path(self):
  327. # Fixed authenticated data, fixed plaintext
  328. # Verify path INIT->UPDATE->ENCRYPT->DIGEST
  329. cipher = AES.new(self.key_128, AES.MODE_GCM,
  330. nonce=self.nonce_96)
  331. cipher.update(self.data_128)
  332. ct = cipher.encrypt(self.data_128)
  333. mac = cipher.digest()
  334. # Verify path INIT->UPDATE->DECRYPT->VERIFY
  335. cipher = AES.new(self.key_128, AES.MODE_GCM,
  336. nonce=self.nonce_96)
  337. cipher.update(self.data_128)
  338. cipher.decrypt(ct)
  339. cipher.verify(mac)
  340. def test_valid_init_digest(self):
  341. # Verify path INIT->DIGEST
  342. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  343. cipher.digest()
  344. def test_valid_init_verify(self):
  345. # Verify path INIT->VERIFY
  346. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  347. mac = cipher.digest()
  348. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  349. cipher.verify(mac)
  350. def test_valid_multiple_encrypt_or_decrypt(self):
  351. for method_name in "encrypt", "decrypt":
  352. for auth_data in (None, b"333", self.data_128,
  353. self.data_128 + b"3"):
  354. if auth_data is None:
  355. assoc_len = None
  356. else:
  357. assoc_len = len(auth_data)
  358. cipher = AES.new(self.key_128, AES.MODE_GCM,
  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 = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  370. cipher.update(self.data_128)
  371. first_mac = cipher.digest()
  372. for x in range(4):
  373. self.assertEqual(first_mac, cipher.digest())
  374. # Multiple calls to verify
  375. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  376. cipher.update(self.data_128)
  377. for x in range(5):
  378. cipher.verify(first_mac)
  379. def test_valid_encrypt_and_digest_decrypt_and_verify(self):
  380. # encrypt_and_digest
  381. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  382. cipher.update(self.data_128)
  383. ct, mac = cipher.encrypt_and_digest(self.data_128)
  384. # decrypt_and_verify
  385. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  386. cipher.update(self.data_128)
  387. pt = cipher.decrypt_and_verify(ct, mac)
  388. self.assertEqual(self.data_128, pt)
  389. def test_invalid_mixing_encrypt_decrypt(self):
  390. # Once per method, with or without assoc. data
  391. for method1_name, method2_name in (("encrypt", "decrypt"),
  392. ("decrypt", "encrypt")):
  393. for assoc_data_present in (True, False):
  394. cipher = AES.new(self.key_128, AES.MODE_GCM,
  395. nonce=self.nonce_96)
  396. if assoc_data_present:
  397. cipher.update(self.data_128)
  398. getattr(cipher, method1_name)(self.data_128)
  399. self.assertRaises(TypeError, getattr(cipher, method2_name),
  400. self.data_128)
  401. def test_invalid_encrypt_or_update_after_digest(self):
  402. for method_name in "encrypt", "update":
  403. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  404. cipher.encrypt(self.data_128)
  405. cipher.digest()
  406. self.assertRaises(TypeError, getattr(cipher, method_name),
  407. self.data_128)
  408. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  409. cipher.encrypt_and_digest(self.data_128)
  410. def test_invalid_decrypt_or_update_after_verify(self):
  411. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  412. ct = cipher.encrypt(self.data_128)
  413. mac = cipher.digest()
  414. for method_name in "decrypt", "update":
  415. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  416. cipher.decrypt(ct)
  417. cipher.verify(mac)
  418. self.assertRaises(TypeError, getattr(cipher, method_name),
  419. self.data_128)
  420. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  421. cipher.decrypt_and_verify(ct, mac)
  422. self.assertRaises(TypeError, getattr(cipher, method_name),
  423. self.data_128)
  424. class TestVectors(unittest.TestCase):
  425. """Class exercising the GCM test vectors found in
  426. http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/gcm/gcm-revised-spec.pdf"""
  427. # List of test vectors, each made up of:
  428. # - authenticated data
  429. # - plaintext
  430. # - ciphertext
  431. # - MAC
  432. # - AES key
  433. # - nonce
  434. test_vectors_hex = [
  435. (
  436. '',
  437. '',
  438. '',
  439. '58e2fccefa7e3061367f1d57a4e7455a',
  440. '00000000000000000000000000000000',
  441. '000000000000000000000000'
  442. ),
  443. (
  444. '',
  445. '00000000000000000000000000000000',
  446. '0388dace60b6a392f328c2b971b2fe78',
  447. 'ab6e47d42cec13bdf53a67b21257bddf',
  448. '00000000000000000000000000000000',
  449. '000000000000000000000000'
  450. ),
  451. (
  452. '',
  453. 'd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72' +
  454. '1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b391aafd255',
  455. '42831ec2217774244b7221b784d0d49ce3aa212f2c02a4e035c17e2329aca12e' +
  456. '21d514b25466931c7d8f6a5aac84aa051ba30b396a0aac973d58e091473f5985',
  457. '4d5c2af327cd64a62cf35abd2ba6fab4',
  458. 'feffe9928665731c6d6a8f9467308308',
  459. 'cafebabefacedbaddecaf888'
  460. ),
  461. (
  462. 'feedfacedeadbeeffeedfacedeadbeefabaddad2',
  463. 'd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72' +
  464. '1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39',
  465. '42831ec2217774244b7221b784d0d49ce3aa212f2c02a4e035c17e2329aca12e' +
  466. '21d514b25466931c7d8f6a5aac84aa051ba30b396a0aac973d58e091',
  467. '5bc94fbc3221a5db94fae95ae7121a47',
  468. 'feffe9928665731c6d6a8f9467308308',
  469. 'cafebabefacedbaddecaf888'
  470. ),
  471. (
  472. 'feedfacedeadbeeffeedfacedeadbeefabaddad2',
  473. 'd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72' +
  474. '1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39',
  475. '61353b4c2806934a777ff51fa22a4755699b2a714fcdc6f83766e5f97b6c7423' +
  476. '73806900e49f24b22b097544d4896b424989b5e1ebac0f07c23f4598',
  477. '3612d2e79e3b0785561be14aaca2fccb',
  478. 'feffe9928665731c6d6a8f9467308308',
  479. 'cafebabefacedbad'
  480. ),
  481. (
  482. 'feedfacedeadbeeffeedfacedeadbeefabaddad2',
  483. 'd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72' +
  484. '1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39',
  485. '8ce24998625615b603a033aca13fb894be9112a5c3a211a8ba262a3cca7e2ca7' +
  486. '01e4a9a4fba43c90ccdcb281d48c7c6fd62875d2aca417034c34aee5',
  487. '619cc5aefffe0bfa462af43c1699d050',
  488. 'feffe9928665731c6d6a8f9467308308',
  489. '9313225df88406e555909c5aff5269aa' +
  490. '6a7a9538534f7da1e4c303d2a318a728c3c0c95156809539fcf0e2429a6b5254'+
  491. '16aedbf5a0de6a57a637b39b'
  492. ),
  493. (
  494. '',
  495. '',
  496. '',
  497. 'cd33b28ac773f74ba00ed1f312572435',
  498. '000000000000000000000000000000000000000000000000',
  499. '000000000000000000000000'
  500. ),
  501. (
  502. '',
  503. '00000000000000000000000000000000',
  504. '98e7247c07f0fe411c267e4384b0f600',
  505. '2ff58d80033927ab8ef4d4587514f0fb',
  506. '000000000000000000000000000000000000000000000000',
  507. '000000000000000000000000'
  508. ),
  509. (
  510. '',
  511. 'd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72' +
  512. '1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b391aafd255',
  513. '3980ca0b3c00e841eb06fac4872a2757859e1ceaa6efd984628593b40ca1e19c' +
  514. '7d773d00c144c525ac619d18c84a3f4718e2448b2fe324d9ccda2710acade256',
  515. '9924a7c8587336bfb118024db8674a14',
  516. 'feffe9928665731c6d6a8f9467308308feffe9928665731c',
  517. 'cafebabefacedbaddecaf888'
  518. ),
  519. (
  520. 'feedfacedeadbeeffeedfacedeadbeefabaddad2',
  521. 'd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72' +
  522. '1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39',
  523. '3980ca0b3c00e841eb06fac4872a2757859e1ceaa6efd984628593b40ca1e19c' +
  524. '7d773d00c144c525ac619d18c84a3f4718e2448b2fe324d9ccda2710',
  525. '2519498e80f1478f37ba55bd6d27618c',
  526. 'feffe9928665731c6d6a8f9467308308feffe9928665731c',
  527. 'cafebabefacedbaddecaf888'
  528. ),
  529. (
  530. 'feedfacedeadbeeffeedfacedeadbeefabaddad2',
  531. 'd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72' +
  532. '1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39',
  533. '0f10f599ae14a154ed24b36e25324db8c566632ef2bbb34f8347280fc4507057' +
  534. 'fddc29df9a471f75c66541d4d4dad1c9e93a19a58e8b473fa0f062f7',
  535. '65dcc57fcf623a24094fcca40d3533f8',
  536. 'feffe9928665731c6d6a8f9467308308feffe9928665731c',
  537. 'cafebabefacedbad'
  538. ),
  539. (
  540. 'feedfacedeadbeeffeedfacedeadbeefabaddad2',
  541. 'd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72' +
  542. '1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39',
  543. 'd27e88681ce3243c4830165a8fdcf9ff1de9a1d8e6b447ef6ef7b79828666e45' +
  544. '81e79012af34ddd9e2f037589b292db3e67c036745fa22e7e9b7373b',
  545. 'dcf566ff291c25bbb8568fc3d376a6d9',
  546. 'feffe9928665731c6d6a8f9467308308feffe9928665731c',
  547. '9313225df88406e555909c5aff5269aa' +
  548. '6a7a9538534f7da1e4c303d2a318a728c3c0c95156809539fcf0e2429a6b5254' +
  549. '16aedbf5a0de6a57a637b39b'
  550. ),
  551. (
  552. '',
  553. '',
  554. '',
  555. '530f8afbc74536b9a963b4f1c4cb738b',
  556. '0000000000000000000000000000000000000000000000000000000000000000',
  557. '000000000000000000000000'
  558. ),
  559. (
  560. '',
  561. '00000000000000000000000000000000',
  562. 'cea7403d4d606b6e074ec5d3baf39d18',
  563. 'd0d1c8a799996bf0265b98b5d48ab919',
  564. '0000000000000000000000000000000000000000000000000000000000000000',
  565. '000000000000000000000000'
  566. ),
  567. ( '',
  568. 'd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72' +
  569. '1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b391aafd255',
  570. '522dc1f099567d07f47f37a32a84427d643a8cdcbfe5c0c97598a2bd2555d1aa' +
  571. '8cb08e48590dbb3da7b08b1056828838c5f61e6393ba7a0abcc9f662898015ad',
  572. 'b094dac5d93471bdec1a502270e3cc6c',
  573. 'feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308',
  574. 'cafebabefacedbaddecaf888'
  575. ),
  576. (
  577. 'feedfacedeadbeeffeedfacedeadbeefabaddad2',
  578. 'd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72' +
  579. '1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39',
  580. '522dc1f099567d07f47f37a32a84427d643a8cdcbfe5c0c97598a2bd2555d1aa' +
  581. '8cb08e48590dbb3da7b08b1056828838c5f61e6393ba7a0abcc9f662',
  582. '76fc6ece0f4e1768cddf8853bb2d551b',
  583. 'feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308',
  584. 'cafebabefacedbaddecaf888'
  585. ),
  586. (
  587. 'feedfacedeadbeeffeedfacedeadbeefabaddad2',
  588. 'd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72' +
  589. '1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39',
  590. 'c3762df1ca787d32ae47c13bf19844cbaf1ae14d0b976afac52ff7d79bba9de0' +
  591. 'feb582d33934a4f0954cc2363bc73f7862ac430e64abe499f47c9b1f',
  592. '3a337dbf46a792c45e454913fe2ea8f2',
  593. 'feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308',
  594. 'cafebabefacedbad'
  595. ),
  596. (
  597. 'feedfacedeadbeeffeedfacedeadbeefabaddad2',
  598. 'd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72' +
  599. '1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39',
  600. '5a8def2f0c9e53f1f75d7853659e2a20eeb2b22aafde6419a058ab4f6f746bf4' +
  601. '0fc0c3b780f244452da3ebf1c5d82cdea2418997200ef82e44ae7e3f',
  602. 'a44a8266ee1c8eb0c8b5d4cf5ae9f19a',
  603. 'feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308',
  604. '9313225df88406e555909c5aff5269aa' +
  605. '6a7a9538534f7da1e4c303d2a318a728c3c0c95156809539fcf0e2429a6b5254'+
  606. '16aedbf5a0de6a57a637b39b'
  607. )
  608. ]
  609. test_vectors = [[unhexlify(x) for x in tv] for tv in test_vectors_hex]
  610. def runTest(self):
  611. for assoc_data, pt, ct, mac, key, nonce in self.test_vectors:
  612. # Encrypt
  613. cipher = AES.new(key, AES.MODE_GCM, nonce, mac_len=len(mac))
  614. cipher.update(assoc_data)
  615. ct2, mac2 = cipher.encrypt_and_digest(pt)
  616. self.assertEqual(ct, ct2)
  617. self.assertEqual(mac, mac2)
  618. # Decrypt
  619. cipher = AES.new(key, AES.MODE_GCM, nonce, mac_len=len(mac))
  620. cipher.update(assoc_data)
  621. pt2 = cipher.decrypt_and_verify(ct, mac)
  622. self.assertEqual(pt, pt2)
  623. class TestVectorsGueronKrasnov(unittest.TestCase):
  624. """Class exercising the GCM test vectors found in
  625. 'The fragility of AES-GCM authentication algorithm', Gueron, Krasnov
  626. https://eprint.iacr.org/2013/157.pdf"""
  627. def test_1(self):
  628. key = unhexlify("3da6c536d6295579c0959a7043efb503")
  629. iv = unhexlify("2b926197d34e091ef722db94")
  630. aad = unhexlify("00000000000000000000000000000000" +
  631. "000102030405060708090a0b0c0d0e0f" +
  632. "101112131415161718191a1b1c1d1e1f" +
  633. "202122232425262728292a2b2c2d2e2f" +
  634. "303132333435363738393a3b3c3d3e3f")
  635. digest = unhexlify("69dd586555ce3fcc89663801a71d957b")
  636. cipher = AES.new(key, AES.MODE_GCM, iv).update(aad)
  637. self.assertEqual(digest, cipher.digest())
  638. def test_2(self):
  639. key = unhexlify("843ffcf5d2b72694d19ed01d01249412")
  640. iv = unhexlify("dbcca32ebf9b804617c3aa9e")
  641. aad = unhexlify("00000000000000000000000000000000" +
  642. "101112131415161718191a1b1c1d1e1f")
  643. pt = unhexlify("000102030405060708090a0b0c0d0e0f" +
  644. "101112131415161718191a1b1c1d1e1f" +
  645. "202122232425262728292a2b2c2d2e2f" +
  646. "303132333435363738393a3b3c3d3e3f" +
  647. "404142434445464748494a4b4c4d4e4f")
  648. ct = unhexlify("6268c6fa2a80b2d137467f092f657ac0" +
  649. "4d89be2beaa623d61b5a868c8f03ff95" +
  650. "d3dcee23ad2f1ab3a6c80eaf4b140eb0" +
  651. "5de3457f0fbc111a6b43d0763aa422a3" +
  652. "013cf1dc37fe417d1fbfc449b75d4cc5")
  653. digest = unhexlify("3b629ccfbc1119b7319e1dce2cd6fd6d")
  654. cipher = AES.new(key, AES.MODE_GCM, iv).update(aad)
  655. ct2, digest2 = cipher.encrypt_and_digest(pt)
  656. self.assertEqual(ct, ct2)
  657. self.assertEqual(digest, digest2)
  658. class NISTTestVectorsGCM(unittest.TestCase):
  659. def __init__(self, a):
  660. self.use_clmul = True
  661. unittest.TestCase.__init__(self, a)
  662. class NISTTestVectorsGCM_no_clmul(unittest.TestCase):
  663. def __init__(self, a):
  664. self.use_clmul = False
  665. unittest.TestCase.__init__(self, a)
  666. test_vectors_nist = load_tests(
  667. ("Crypto", "SelfTest", "Cipher", "test_vectors", "AES"),
  668. "gcmDecrypt128.rsp",
  669. "GCM decrypt",
  670. { "count" : lambda x: int(x) })
  671. test_vectors_nist += load_tests(
  672. ("Crypto", "SelfTest", "Cipher", "test_vectors", "AES"),
  673. "gcmEncryptExtIV128.rsp",
  674. "GCM encrypt",
  675. { "count" : lambda x: int(x) })
  676. for idx, tv in enumerate(test_vectors_nist):
  677. # The test vector file contains some directive lines
  678. if isinstance(tv, str):
  679. continue
  680. def single_test(self, tv=tv):
  681. self.description = tv.desc
  682. cipher = AES.new(tv.key, AES.MODE_GCM, nonce=tv.iv,
  683. mac_len=len(tv.tag), use_clmul=self.use_clmul)
  684. cipher.update(tv.aad)
  685. if "FAIL" in tv.others:
  686. self.assertRaises(ValueError, cipher.decrypt_and_verify,
  687. tv.ct, tv.tag)
  688. else:
  689. pt = cipher.decrypt_and_verify(tv.ct, tv.tag)
  690. self.assertEqual(pt, tv.pt)
  691. setattr(NISTTestVectorsGCM, "test_%d" % idx, single_test)
  692. setattr(NISTTestVectorsGCM_no_clmul, "test_%d" % idx, single_test)
  693. class TestVectorsWycheproof(unittest.TestCase):
  694. def __init__(self, wycheproof_warnings, **extra_params):
  695. unittest.TestCase.__init__(self)
  696. self._wycheproof_warnings = wycheproof_warnings
  697. self._extra_params = extra_params
  698. self._id = "None"
  699. def setUp(self):
  700. comps = "Crypto.SelfTest.Cipher.test_vectors.wycheproof".split(".")
  701. with open(pycryptodome_filename(comps, "aes_gcm_test.json"), "rt") as file_in:
  702. tv_tree = json.load(file_in)
  703. class TestVector(object):
  704. pass
  705. self.tv = []
  706. for group in tv_tree['testGroups']:
  707. tag_size = group['tagSize'] // 8
  708. for test in group['tests']:
  709. tv = TestVector()
  710. tv.tag_size = tag_size
  711. tv.id = test['tcId']
  712. tv.comment = test['comment']
  713. for attr in 'key', 'iv', 'aad', 'msg', 'ct', 'tag':
  714. setattr(tv, attr, unhexlify(test[attr]))
  715. tv.valid = test['result'] != "invalid"
  716. tv.warning = test['result'] == "acceptable"
  717. self.tv.append(tv)
  718. def shortDescription(self):
  719. return self._id
  720. def warn(self, tv):
  721. if tv.warning and self._wycheproof_warnings:
  722. import warnings
  723. warnings.warn("Wycheproof warning: %s (%s)" % (self._id, tv.comment))
  724. def test_encrypt(self, tv):
  725. self._id = "Wycheproof Encrypt GCM Test #" + str(tv.id)
  726. try:
  727. cipher = AES.new(tv.key, AES.MODE_GCM, tv.iv, mac_len=tv.tag_size,
  728. **self._extra_params)
  729. except ValueError as e:
  730. if len(tv.iv) == 0 and "Nonce cannot be empty" in str(e):
  731. return
  732. raise e
  733. cipher.update(tv.aad)
  734. ct, tag = cipher.encrypt_and_digest(tv.msg)
  735. if tv.valid:
  736. self.assertEqual(ct, tv.ct)
  737. self.assertEqual(tag, tv.tag)
  738. self.warn(tv)
  739. def test_decrypt(self, tv):
  740. self._id = "Wycheproof Decrypt GCM Test #" + str(tv.id)
  741. try:
  742. cipher = AES.new(tv.key, AES.MODE_GCM, tv.iv, mac_len=tv.tag_size,
  743. **self._extra_params)
  744. except ValueError as e:
  745. if len(tv.iv) == 0 and "Nonce cannot be empty" in str(e):
  746. return
  747. raise e
  748. cipher.update(tv.aad)
  749. try:
  750. pt = cipher.decrypt_and_verify(tv.ct, tv.tag)
  751. except ValueError:
  752. assert not tv.valid
  753. else:
  754. assert tv.valid
  755. self.assertEqual(pt, tv.msg)
  756. self.warn(tv)
  757. def test_corrupt_decrypt(self, tv):
  758. self._id = "Wycheproof Corrupt Decrypt GCM Test #" + str(tv.id)
  759. if len(tv.iv) == 0 or len(tv.ct) < 1:
  760. return
  761. cipher = AES.new(tv.key, AES.MODE_GCM, tv.iv, mac_len=tv.tag_size,
  762. **self._extra_params)
  763. cipher.update(tv.aad)
  764. ct_corrupt = strxor(tv.ct, b"\x00" * (len(tv.ct) - 1) + b"\x01")
  765. self.assertRaises(ValueError, cipher.decrypt_and_verify, ct_corrupt, tv.tag)
  766. def runTest(self):
  767. for tv in self.tv:
  768. self.test_encrypt(tv)
  769. self.test_decrypt(tv)
  770. self.test_corrupt_decrypt(tv)
  771. class TestVariableLength(unittest.TestCase):
  772. def __init__(self, **extra_params):
  773. unittest.TestCase.__init__(self)
  774. self._extra_params = extra_params
  775. def runTest(self):
  776. key = b'0' * 16
  777. h = SHA256.new()
  778. for length in range(160):
  779. nonce = '{0:04d}'.format(length).encode('utf-8')
  780. data = bchr(length) * length
  781. cipher = AES.new(key, AES.MODE_GCM, nonce=nonce, **self._extra_params)
  782. ct, tag = cipher.encrypt_and_digest(data)
  783. h.update(ct)
  784. h.update(tag)
  785. self.assertEqual(h.hexdigest(), "7b7eb1ffbe67a2e53a912067c0ec8e62ebc7ce4d83490ea7426941349811bdf4")
  786. def get_tests(config={}):
  787. from tls.Crypto.Util import _cpu_features
  788. wycheproof_warnings = config.get('wycheproof_warnings')
  789. tests = []
  790. tests += list_test_cases(GcmTests)
  791. tests += list_test_cases(GcmFSMTests)
  792. tests += [ TestVectors() ]
  793. tests += [ TestVectorsWycheproof(wycheproof_warnings) ]
  794. tests += list_test_cases(TestVectorsGueronKrasnov)
  795. tests += [ TestVariableLength() ]
  796. if config.get('slow_tests'):
  797. tests += list_test_cases(NISTTestVectorsGCM)
  798. if _cpu_features.have_clmul():
  799. tests += [ TestVectorsWycheproof(wycheproof_warnings, use_clmul=False) ]
  800. tests += [ TestVariableLength(use_clmul = False) ]
  801. if config.get('slow_tests'):
  802. tests += list_test_cases(NISTTestVectorsGCM_no_clmul)
  803. else:
  804. print("Skipping test of PCLMULDQD in AES GCM")
  805. return tests
  806. if __name__ == '__main__':
  807. suite = lambda: unittest.TestSuite(get_tests())
  808. unittest.main(defaultTest='suite')