test_GCM.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951
  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 = get_tag_random("data", 128)
  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)
  57. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  58. self.assertEqual(ct, cipher.encrypt(self.data))
  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)
  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)
  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)
  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.assertEqual(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)
  172. data_ba = bytearray(self.data)
  173. cipher1 = AES.new(self.key_128,
  174. AES.MODE_GCM,
  175. nonce=self.nonce_96)
  176. cipher1.update(self.data)
  177. ct = cipher1.encrypt(self.data)
  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)
  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, 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))
  211. data_mv = memoryview(bytearray(self.data))
  212. cipher1 = AES.new(self.key_128,
  213. AES.MODE_GCM,
  214. nonce=self.nonce_96)
  215. cipher1.update(self.data)
  216. ct = cipher1.encrypt(self.data)
  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))
  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, pt_test)
  245. def test_output_param(self):
  246. pt = b'5' * 128
  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(128)
  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' * 128
  270. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  271. ct = cipher.encrypt(pt)
  272. output = memoryview(bytearray(128))
  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. LEN_PT = 128
  281. pt = b'5' * LEN_PT
  282. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  283. ct = cipher.encrypt(pt)
  284. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  285. self.assertRaises(TypeError, cipher.encrypt, pt, output=b'0' * LEN_PT)
  286. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  287. self.assertRaises(TypeError, cipher.decrypt, ct, output=b'0' * LEN_PT)
  288. shorter_output = bytearray(LEN_PT - 1)
  289. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  290. self.assertRaises(ValueError, cipher.encrypt, pt, output=shorter_output)
  291. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  292. self.assertRaises(ValueError, cipher.decrypt, ct, output=shorter_output)
  293. class GcmFSMTests(unittest.TestCase):
  294. key_128 = get_tag_random("key_128", 16)
  295. nonce_96 = get_tag_random("nonce_128", 12)
  296. data = get_tag_random("data", 128)
  297. def test_valid_init_encrypt_decrypt_digest_verify(self):
  298. # No authenticated data, fixed plaintext
  299. # Verify path INIT->ENCRYPT->DIGEST
  300. cipher = AES.new(self.key_128, AES.MODE_GCM,
  301. nonce=self.nonce_96)
  302. ct = cipher.encrypt(self.data)
  303. mac = cipher.digest()
  304. # Verify path INIT->DECRYPT->VERIFY
  305. cipher = AES.new(self.key_128, AES.MODE_GCM,
  306. nonce=self.nonce_96)
  307. cipher.decrypt(ct)
  308. cipher.verify(mac)
  309. def test_valid_init_update_digest_verify(self):
  310. # No plaintext, fixed authenticated data
  311. # Verify path INIT->UPDATE->DIGEST
  312. cipher = AES.new(self.key_128, AES.MODE_GCM,
  313. nonce=self.nonce_96)
  314. cipher.update(self.data)
  315. mac = cipher.digest()
  316. # Verify path INIT->UPDATE->VERIFY
  317. cipher = AES.new(self.key_128, AES.MODE_GCM,
  318. nonce=self.nonce_96)
  319. cipher.update(self.data)
  320. cipher.verify(mac)
  321. def test_valid_full_path(self):
  322. # Fixed authenticated data, fixed plaintext
  323. # Verify path INIT->UPDATE->ENCRYPT->DIGEST
  324. cipher = AES.new(self.key_128, AES.MODE_GCM,
  325. nonce=self.nonce_96)
  326. cipher.update(self.data)
  327. ct = cipher.encrypt(self.data)
  328. mac = cipher.digest()
  329. # Verify path INIT->UPDATE->DECRYPT->VERIFY
  330. cipher = AES.new(self.key_128, AES.MODE_GCM,
  331. nonce=self.nonce_96)
  332. cipher.update(self.data)
  333. cipher.decrypt(ct)
  334. cipher.verify(mac)
  335. def test_valid_init_digest(self):
  336. # Verify path INIT->DIGEST
  337. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  338. cipher.digest()
  339. def test_valid_init_verify(self):
  340. # Verify path INIT->VERIFY
  341. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  342. mac = cipher.digest()
  343. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  344. cipher.verify(mac)
  345. def test_valid_multiple_encrypt_or_decrypt(self):
  346. for method_name in "encrypt", "decrypt":
  347. for auth_data in (None, b"333", self.data,
  348. self.data + b"3"):
  349. if auth_data is None:
  350. assoc_len = None
  351. else:
  352. assoc_len = len(auth_data)
  353. cipher = AES.new(self.key_128, AES.MODE_GCM,
  354. nonce=self.nonce_96)
  355. if auth_data is not None:
  356. cipher.update(auth_data)
  357. method = getattr(cipher, method_name)
  358. method(self.data)
  359. method(self.data)
  360. method(self.data)
  361. method(self.data)
  362. def test_valid_multiple_digest_or_verify(self):
  363. # Multiple calls to digest
  364. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  365. cipher.update(self.data)
  366. first_mac = cipher.digest()
  367. for x in range(4):
  368. self.assertEqual(first_mac, cipher.digest())
  369. # Multiple calls to verify
  370. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  371. cipher.update(self.data)
  372. for x in range(5):
  373. cipher.verify(first_mac)
  374. def test_valid_encrypt_and_digest_decrypt_and_verify(self):
  375. # encrypt_and_digest
  376. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  377. cipher.update(self.data)
  378. ct, mac = cipher.encrypt_and_digest(self.data)
  379. # decrypt_and_verify
  380. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  381. cipher.update(self.data)
  382. pt = cipher.decrypt_and_verify(ct, mac)
  383. self.assertEqual(self.data, pt)
  384. def test_invalid_mixing_encrypt_decrypt(self):
  385. # Once per method, with or without assoc. data
  386. for method1_name, method2_name in (("encrypt", "decrypt"),
  387. ("decrypt", "encrypt")):
  388. for assoc_data_present in (True, False):
  389. cipher = AES.new(self.key_128, AES.MODE_GCM,
  390. nonce=self.nonce_96)
  391. if assoc_data_present:
  392. cipher.update(self.data)
  393. getattr(cipher, method1_name)(self.data)
  394. self.assertRaises(TypeError, getattr(cipher, method2_name),
  395. self.data)
  396. def test_invalid_encrypt_or_update_after_digest(self):
  397. for method_name in "encrypt", "update":
  398. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  399. cipher.encrypt(self.data)
  400. cipher.digest()
  401. self.assertRaises(TypeError, getattr(cipher, method_name),
  402. self.data)
  403. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  404. cipher.encrypt_and_digest(self.data)
  405. def test_invalid_decrypt_or_update_after_verify(self):
  406. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  407. ct = cipher.encrypt(self.data)
  408. mac = cipher.digest()
  409. for method_name in "decrypt", "update":
  410. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  411. cipher.decrypt(ct)
  412. cipher.verify(mac)
  413. self.assertRaises(TypeError, getattr(cipher, method_name),
  414. self.data)
  415. cipher = AES.new(self.key_128, AES.MODE_GCM, nonce=self.nonce_96)
  416. cipher.decrypt_and_verify(ct, mac)
  417. self.assertRaises(TypeError, getattr(cipher, method_name),
  418. self.data)
  419. class TestVectors(unittest.TestCase):
  420. """Class exercising the GCM test vectors found in
  421. http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/gcm/gcm-revised-spec.pdf"""
  422. # List of test vectors, each made up of:
  423. # - authenticated data
  424. # - plaintext
  425. # - ciphertext
  426. # - MAC
  427. # - AES key
  428. # - nonce
  429. test_vectors_hex = [
  430. (
  431. '',
  432. '',
  433. '',
  434. '58e2fccefa7e3061367f1d57a4e7455a',
  435. '00000000000000000000000000000000',
  436. '000000000000000000000000'
  437. ),
  438. (
  439. '',
  440. '00000000000000000000000000000000',
  441. '0388dace60b6a392f328c2b971b2fe78',
  442. 'ab6e47d42cec13bdf53a67b21257bddf',
  443. '00000000000000000000000000000000',
  444. '000000000000000000000000'
  445. ),
  446. (
  447. '',
  448. 'd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72' +
  449. '1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b391aafd255',
  450. '42831ec2217774244b7221b784d0d49ce3aa212f2c02a4e035c17e2329aca12e' +
  451. '21d514b25466931c7d8f6a5aac84aa051ba30b396a0aac973d58e091473f5985',
  452. '4d5c2af327cd64a62cf35abd2ba6fab4',
  453. 'feffe9928665731c6d6a8f9467308308',
  454. 'cafebabefacedbaddecaf888'
  455. ),
  456. (
  457. 'feedfacedeadbeeffeedfacedeadbeefabaddad2',
  458. 'd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72' +
  459. '1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39',
  460. '42831ec2217774244b7221b784d0d49ce3aa212f2c02a4e035c17e2329aca12e' +
  461. '21d514b25466931c7d8f6a5aac84aa051ba30b396a0aac973d58e091',
  462. '5bc94fbc3221a5db94fae95ae7121a47',
  463. 'feffe9928665731c6d6a8f9467308308',
  464. 'cafebabefacedbaddecaf888'
  465. ),
  466. (
  467. 'feedfacedeadbeeffeedfacedeadbeefabaddad2',
  468. 'd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72' +
  469. '1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39',
  470. '61353b4c2806934a777ff51fa22a4755699b2a714fcdc6f83766e5f97b6c7423' +
  471. '73806900e49f24b22b097544d4896b424989b5e1ebac0f07c23f4598',
  472. '3612d2e79e3b0785561be14aaca2fccb',
  473. 'feffe9928665731c6d6a8f9467308308',
  474. 'cafebabefacedbad'
  475. ),
  476. (
  477. 'feedfacedeadbeeffeedfacedeadbeefabaddad2',
  478. 'd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72' +
  479. '1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39',
  480. '8ce24998625615b603a033aca13fb894be9112a5c3a211a8ba262a3cca7e2ca7' +
  481. '01e4a9a4fba43c90ccdcb281d48c7c6fd62875d2aca417034c34aee5',
  482. '619cc5aefffe0bfa462af43c1699d050',
  483. 'feffe9928665731c6d6a8f9467308308',
  484. '9313225df88406e555909c5aff5269aa' +
  485. '6a7a9538534f7da1e4c303d2a318a728c3c0c95156809539fcf0e2429a6b5254' +
  486. '16aedbf5a0de6a57a637b39b'
  487. ),
  488. (
  489. '',
  490. '',
  491. '',
  492. 'cd33b28ac773f74ba00ed1f312572435',
  493. '000000000000000000000000000000000000000000000000',
  494. '000000000000000000000000'
  495. ),
  496. (
  497. '',
  498. '00000000000000000000000000000000',
  499. '98e7247c07f0fe411c267e4384b0f600',
  500. '2ff58d80033927ab8ef4d4587514f0fb',
  501. '000000000000000000000000000000000000000000000000',
  502. '000000000000000000000000'
  503. ),
  504. (
  505. '',
  506. 'd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72' +
  507. '1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b391aafd255',
  508. '3980ca0b3c00e841eb06fac4872a2757859e1ceaa6efd984628593b40ca1e19c' +
  509. '7d773d00c144c525ac619d18c84a3f4718e2448b2fe324d9ccda2710acade256',
  510. '9924a7c8587336bfb118024db8674a14',
  511. 'feffe9928665731c6d6a8f9467308308feffe9928665731c',
  512. 'cafebabefacedbaddecaf888'
  513. ),
  514. (
  515. 'feedfacedeadbeeffeedfacedeadbeefabaddad2',
  516. 'd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72' +
  517. '1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39',
  518. '3980ca0b3c00e841eb06fac4872a2757859e1ceaa6efd984628593b40ca1e19c' +
  519. '7d773d00c144c525ac619d18c84a3f4718e2448b2fe324d9ccda2710',
  520. '2519498e80f1478f37ba55bd6d27618c',
  521. 'feffe9928665731c6d6a8f9467308308feffe9928665731c',
  522. 'cafebabefacedbaddecaf888'
  523. ),
  524. (
  525. 'feedfacedeadbeeffeedfacedeadbeefabaddad2',
  526. 'd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72' +
  527. '1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39',
  528. '0f10f599ae14a154ed24b36e25324db8c566632ef2bbb34f8347280fc4507057' +
  529. 'fddc29df9a471f75c66541d4d4dad1c9e93a19a58e8b473fa0f062f7',
  530. '65dcc57fcf623a24094fcca40d3533f8',
  531. 'feffe9928665731c6d6a8f9467308308feffe9928665731c',
  532. 'cafebabefacedbad'
  533. ),
  534. (
  535. 'feedfacedeadbeeffeedfacedeadbeefabaddad2',
  536. 'd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72' +
  537. '1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39',
  538. 'd27e88681ce3243c4830165a8fdcf9ff1de9a1d8e6b447ef6ef7b79828666e45' +
  539. '81e79012af34ddd9e2f037589b292db3e67c036745fa22e7e9b7373b',
  540. 'dcf566ff291c25bbb8568fc3d376a6d9',
  541. 'feffe9928665731c6d6a8f9467308308feffe9928665731c',
  542. '9313225df88406e555909c5aff5269aa' +
  543. '6a7a9538534f7da1e4c303d2a318a728c3c0c95156809539fcf0e2429a6b5254' +
  544. '16aedbf5a0de6a57a637b39b'
  545. ),
  546. (
  547. '',
  548. '',
  549. '',
  550. '530f8afbc74536b9a963b4f1c4cb738b',
  551. '0000000000000000000000000000000000000000000000000000000000000000',
  552. '000000000000000000000000'
  553. ),
  554. (
  555. '',
  556. '00000000000000000000000000000000',
  557. 'cea7403d4d606b6e074ec5d3baf39d18',
  558. 'd0d1c8a799996bf0265b98b5d48ab919',
  559. '0000000000000000000000000000000000000000000000000000000000000000',
  560. '000000000000000000000000'
  561. ),
  562. ( '',
  563. 'd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72' +
  564. '1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b391aafd255',
  565. '522dc1f099567d07f47f37a32a84427d643a8cdcbfe5c0c97598a2bd2555d1aa' +
  566. '8cb08e48590dbb3da7b08b1056828838c5f61e6393ba7a0abcc9f662898015ad',
  567. 'b094dac5d93471bdec1a502270e3cc6c',
  568. 'feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308',
  569. 'cafebabefacedbaddecaf888'
  570. ),
  571. (
  572. 'feedfacedeadbeeffeedfacedeadbeefabaddad2',
  573. 'd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72' +
  574. '1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39',
  575. '522dc1f099567d07f47f37a32a84427d643a8cdcbfe5c0c97598a2bd2555d1aa' +
  576. '8cb08e48590dbb3da7b08b1056828838c5f61e6393ba7a0abcc9f662',
  577. '76fc6ece0f4e1768cddf8853bb2d551b',
  578. 'feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308',
  579. 'cafebabefacedbaddecaf888'
  580. ),
  581. (
  582. 'feedfacedeadbeeffeedfacedeadbeefabaddad2',
  583. 'd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72' +
  584. '1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39',
  585. 'c3762df1ca787d32ae47c13bf19844cbaf1ae14d0b976afac52ff7d79bba9de0' +
  586. 'feb582d33934a4f0954cc2363bc73f7862ac430e64abe499f47c9b1f',
  587. '3a337dbf46a792c45e454913fe2ea8f2',
  588. 'feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308',
  589. 'cafebabefacedbad'
  590. ),
  591. (
  592. 'feedfacedeadbeeffeedfacedeadbeefabaddad2',
  593. 'd9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72' +
  594. '1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39',
  595. '5a8def2f0c9e53f1f75d7853659e2a20eeb2b22aafde6419a058ab4f6f746bf4' +
  596. '0fc0c3b780f244452da3ebf1c5d82cdea2418997200ef82e44ae7e3f',
  597. 'a44a8266ee1c8eb0c8b5d4cf5ae9f19a',
  598. 'feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308',
  599. '9313225df88406e555909c5aff5269aa' +
  600. '6a7a9538534f7da1e4c303d2a318a728c3c0c95156809539fcf0e2429a6b5254' +
  601. '16aedbf5a0de6a57a637b39b'
  602. )
  603. ]
  604. test_vectors = [[unhexlify(x) for x in tv] for tv in test_vectors_hex]
  605. def runTest(self):
  606. for assoc_data, pt, ct, mac, key, nonce in self.test_vectors:
  607. # Encrypt
  608. cipher = AES.new(key, AES.MODE_GCM, nonce, mac_len=len(mac))
  609. cipher.update(assoc_data)
  610. ct2, mac2 = cipher.encrypt_and_digest(pt)
  611. self.assertEqual(ct, ct2)
  612. self.assertEqual(mac, mac2)
  613. # Decrypt
  614. cipher = AES.new(key, AES.MODE_GCM, nonce, mac_len=len(mac))
  615. cipher.update(assoc_data)
  616. pt2 = cipher.decrypt_and_verify(ct, mac)
  617. self.assertEqual(pt, pt2)
  618. class TestVectorsGueronKrasnov(unittest.TestCase):
  619. """Class exercising the GCM test vectors found in
  620. 'The fragility of AES-GCM authentication algorithm', Gueron, Krasnov
  621. https://eprint.iacr.org/2013/157.pdf"""
  622. def test_1(self):
  623. key = unhexlify("3da6c536d6295579c0959a7043efb503")
  624. iv = unhexlify("2b926197d34e091ef722db94")
  625. aad = unhexlify("00000000000000000000000000000000" +
  626. "000102030405060708090a0b0c0d0e0f" +
  627. "101112131415161718191a1b1c1d1e1f" +
  628. "202122232425262728292a2b2c2d2e2f" +
  629. "303132333435363738393a3b3c3d3e3f")
  630. digest = unhexlify("69dd586555ce3fcc89663801a71d957b")
  631. cipher = AES.new(key, AES.MODE_GCM, iv).update(aad)
  632. self.assertEqual(digest, cipher.digest())
  633. def test_2(self):
  634. key = unhexlify("843ffcf5d2b72694d19ed01d01249412")
  635. iv = unhexlify("dbcca32ebf9b804617c3aa9e")
  636. aad = unhexlify("00000000000000000000000000000000" +
  637. "101112131415161718191a1b1c1d1e1f")
  638. pt = unhexlify("000102030405060708090a0b0c0d0e0f" +
  639. "101112131415161718191a1b1c1d1e1f" +
  640. "202122232425262728292a2b2c2d2e2f" +
  641. "303132333435363738393a3b3c3d3e3f" +
  642. "404142434445464748494a4b4c4d4e4f")
  643. ct = unhexlify("6268c6fa2a80b2d137467f092f657ac0" +
  644. "4d89be2beaa623d61b5a868c8f03ff95" +
  645. "d3dcee23ad2f1ab3a6c80eaf4b140eb0" +
  646. "5de3457f0fbc111a6b43d0763aa422a3" +
  647. "013cf1dc37fe417d1fbfc449b75d4cc5")
  648. digest = unhexlify("3b629ccfbc1119b7319e1dce2cd6fd6d")
  649. cipher = AES.new(key, AES.MODE_GCM, iv).update(aad)
  650. ct2, digest2 = cipher.encrypt_and_digest(pt)
  651. self.assertEqual(ct, ct2)
  652. self.assertEqual(digest, digest2)
  653. class NISTTestVectorsGCM(unittest.TestCase):
  654. def __init__(self, a):
  655. self.use_clmul = True
  656. unittest.TestCase.__init__(self, a)
  657. class NISTTestVectorsGCM_no_clmul(unittest.TestCase):
  658. def __init__(self, a):
  659. self.use_clmul = False
  660. unittest.TestCase.__init__(self, a)
  661. test_vectors_nist = load_test_vectors(
  662. ("Cipher", "AES"),
  663. "gcmDecrypt128.rsp",
  664. "GCM decrypt",
  665. {"count": lambda x: int(x)}) or []
  666. test_vectors_nist += load_test_vectors(
  667. ("Cipher", "AES"),
  668. "gcmEncryptExtIV128.rsp",
  669. "GCM encrypt",
  670. {"count": lambda x: int(x)}) or []
  671. for idx, tv in enumerate(test_vectors_nist):
  672. # The test vector file contains some directive lines
  673. if isinstance(tv, str):
  674. continue
  675. def single_test(self, tv=tv):
  676. self.description = tv.desc
  677. cipher = AES.new(tv.key, AES.MODE_GCM, nonce=tv.iv,
  678. mac_len=len(tv.tag), use_clmul=self.use_clmul)
  679. cipher.update(tv.aad)
  680. if "FAIL" in tv.others:
  681. self.assertRaises(ValueError, cipher.decrypt_and_verify,
  682. tv.ct, tv.tag)
  683. else:
  684. pt = cipher.decrypt_and_verify(tv.ct, tv.tag)
  685. self.assertEqual(pt, tv.pt)
  686. setattr(NISTTestVectorsGCM, "test_%d" % idx, single_test)
  687. setattr(NISTTestVectorsGCM_no_clmul, "test_%d" % idx, single_test)
  688. class TestVectorsWycheproof(unittest.TestCase):
  689. def __init__(self, wycheproof_warnings, **extra_params):
  690. unittest.TestCase.__init__(self)
  691. self._wycheproof_warnings = wycheproof_warnings
  692. self._extra_params = extra_params
  693. self._id = "None"
  694. def setUp(self):
  695. def filter_tag(group):
  696. return group['tagSize'] // 8
  697. self.tv = load_test_vectors_wycheproof(("Cipher", "wycheproof"),
  698. "aes_gcm_test.json",
  699. "Wycheproof GCM",
  700. group_tag={'tag_size': filter_tag})
  701. def shortDescription(self):
  702. return self._id
  703. def warn(self, tv):
  704. if tv.warning and self._wycheproof_warnings:
  705. import warnings
  706. warnings.warn("Wycheproof warning: %s (%s)" % (self._id, tv.comment))
  707. def test_encrypt(self, tv):
  708. self._id = "Wycheproof Encrypt GCM Test #" + str(tv.id)
  709. try:
  710. cipher = AES.new(tv.key, AES.MODE_GCM, tv.iv, mac_len=tv.tag_size,
  711. **self._extra_params)
  712. except ValueError as e:
  713. if len(tv.iv) == 0 and "Nonce cannot be empty" in str(e):
  714. return
  715. raise e
  716. cipher.update(tv.aad)
  717. ct, tag = cipher.encrypt_and_digest(tv.msg)
  718. if tv.valid:
  719. self.assertEqual(ct, tv.ct)
  720. self.assertEqual(tag, tv.tag)
  721. self.warn(tv)
  722. def test_decrypt(self, tv):
  723. self._id = "Wycheproof Decrypt GCM Test #" + str(tv.id)
  724. try:
  725. cipher = AES.new(tv.key, AES.MODE_GCM, tv.iv, mac_len=tv.tag_size,
  726. **self._extra_params)
  727. except ValueError as e:
  728. if len(tv.iv) == 0 and "Nonce cannot be empty" in str(e):
  729. return
  730. raise e
  731. cipher.update(tv.aad)
  732. try:
  733. pt = cipher.decrypt_and_verify(tv.ct, tv.tag)
  734. except ValueError:
  735. assert not tv.valid
  736. else:
  737. assert tv.valid
  738. self.assertEqual(pt, tv.msg)
  739. self.warn(tv)
  740. def test_corrupt_decrypt(self, tv):
  741. self._id = "Wycheproof Corrupt Decrypt GCM Test #" + str(tv.id)
  742. if len(tv.iv) == 0 or len(tv.ct) < 1:
  743. return
  744. cipher = AES.new(tv.key, AES.MODE_GCM, tv.iv, mac_len=tv.tag_size,
  745. **self._extra_params)
  746. cipher.update(tv.aad)
  747. ct_corrupt = strxor(tv.ct, b"\x00" * (len(tv.ct) - 1) + b"\x01")
  748. self.assertRaises(ValueError, cipher.decrypt_and_verify, ct_corrupt, tv.tag)
  749. def runTest(self):
  750. for tv in self.tv:
  751. self.test_encrypt(tv)
  752. self.test_decrypt(tv)
  753. self.test_corrupt_decrypt(tv)
  754. class TestVariableLength(unittest.TestCase):
  755. def __init__(self, **extra_params):
  756. unittest.TestCase.__init__(self)
  757. self._extra_params = extra_params
  758. def runTest(self):
  759. key = b'0' * 16
  760. h = SHA256.new()
  761. for length in range(160):
  762. nonce = '{0:04d}'.format(length).encode('utf-8')
  763. data = bchr(length) * length
  764. cipher = AES.new(key, AES.MODE_GCM, nonce=nonce, **self._extra_params)
  765. ct, tag = cipher.encrypt_and_digest(data)
  766. h.update(ct)
  767. h.update(tag)
  768. self.assertEqual(h.hexdigest(), "7b7eb1ffbe67a2e53a912067c0ec8e62ebc7ce4d83490ea7426941349811bdf4")
  769. def get_tests(config={}):
  770. from Crypto.Util import _cpu_features
  771. wycheproof_warnings = config.get('wycheproof_warnings')
  772. tests = []
  773. tests += list_test_cases(GcmTests)
  774. tests += list_test_cases(GcmFSMTests)
  775. tests += [TestVectors()]
  776. tests += [TestVectorsWycheproof(wycheproof_warnings)]
  777. tests += list_test_cases(TestVectorsGueronKrasnov)
  778. tests += [TestVariableLength()]
  779. if config.get('slow_tests'):
  780. tests += list_test_cases(NISTTestVectorsGCM)
  781. if _cpu_features.have_clmul():
  782. tests += [TestVectorsWycheproof(wycheproof_warnings, use_clmul=False)]
  783. tests += [TestVariableLength(use_clmul=False)]
  784. if config.get('slow_tests'):
  785. tests += list_test_cases(NISTTestVectorsGCM_no_clmul)
  786. else:
  787. print("Skipping test of PCLMULDQD in AES GCM")
  788. return tests
  789. if __name__ == '__main__':
  790. def suite():
  791. unittest.TestSuite(get_tests())
  792. unittest.main(defaultTest='suite')