test_GCM.py 37 KB

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