_mode_gcm.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. # ===================================================================
  2. #
  3. # Copyright (c) 2014, 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. """
  31. Galois/Counter Mode (GCM).
  32. """
  33. __all__ = ['GcmMode']
  34. from Crypto.Util.py3compat import b, bchr, byte_string, bord, unhexlify
  35. from Crypto.Util.number import long_to_bytes, bytes_to_long
  36. from Crypto.Hash import BLAKE2s
  37. from Crypto.Random import get_random_bytes
  38. from Crypto.Util._raw_api import (load_pycryptodome_raw_lib, VoidPointer,
  39. create_string_buffer, get_raw_buffer,
  40. SmartPointer, c_size_t, expect_byte_string)
  41. _raw_galois_lib = load_pycryptodome_raw_lib("Crypto.Util._galois",
  42. """
  43. int ghash( uint8_t y_out[16],
  44. const uint8_t block_data[],
  45. size_t len,
  46. const uint8_t y_in[16],
  47. const void *exp_key);
  48. int ghash_expand(const uint8_t h[16],
  49. void **ghash_tables);
  50. int ghash_destroy(void *ghash_tables);
  51. """)
  52. class _GHASH(object):
  53. """GHASH function defined in NIST SP 800-38D, Algorithm 2.
  54. If X_1, X_2, .. X_m are the blocks of input data, the function
  55. computes:
  56. X_1*H^{m} + X_2*H^{m-1} + ... + X_m*H
  57. in the Galois field GF(2^256) using the reducing polynomial
  58. (x^128 + x^7 + x^2 + x + 1).
  59. """
  60. def __init__(self, subkey):
  61. assert len(subkey) == 16
  62. expect_byte_string(subkey)
  63. self._exp_key = VoidPointer()
  64. result = _raw_galois_lib.ghash_expand(subkey,
  65. self._exp_key.address_of())
  66. if result:
  67. raise ValueError("Error %d while expanding the GMAC key" % result)
  68. self._exp_key = SmartPointer(self._exp_key.get(),
  69. _raw_galois_lib.ghash_destroy)
  70. # create_string_buffer always returns a string of zeroes
  71. self._last_y = create_string_buffer(16)
  72. def update(self, block_data):
  73. assert len(block_data) % 16 == 0
  74. expect_byte_string(block_data)
  75. result = _raw_galois_lib.ghash(self._last_y,
  76. block_data,
  77. c_size_t(len(block_data)),
  78. self._last_y,
  79. self._exp_key.get())
  80. if result:
  81. raise ValueError("Error %d while updating GMAC" % result)
  82. return self
  83. def digest(self):
  84. return get_raw_buffer(self._last_y)
  85. def enum(**enums):
  86. return type('Enum', (), enums)
  87. MacStatus = enum(PROCESSING_AUTH_DATA=1, PROCESSING_CIPHERTEXT=2)
  88. class GcmMode(object):
  89. """Galois Counter Mode (GCM).
  90. This is an Authenticated Encryption with Associated Data (`AEAD`_) mode.
  91. It provides both confidentiality and authenticity.
  92. The header of the message may be left in the clear, if needed, and it will
  93. still be subject to authentication. The decryption step tells the receiver
  94. if the message comes from a source that really knowns the secret key.
  95. Additionally, decryption detects if any part of the message - including the
  96. header - has been modified or corrupted.
  97. This mode requires a *nonce*.
  98. This mode is only available for ciphers that operate on 128 bits blocks
  99. (e.g. AES but not TDES).
  100. See `NIST SP800-38D`_.
  101. .. _`NIST SP800-38D`: http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf
  102. .. _AEAD: http://blog.cryptographyengineering.com/2012/05/how-to-choose-authenticated-encryption.html
  103. :undocumented: __init__
  104. """
  105. def __init__(self, factory, key, nonce, mac_len, cipher_params):
  106. self.block_size = factory.block_size
  107. if self.block_size != 16:
  108. raise ValueError("GCM mode is only available for ciphers"
  109. " that operate on 128 bits blocks")
  110. if len(nonce) == 0:
  111. raise ValueError("Nonce cannot be empty")
  112. if not byte_string(nonce):
  113. raise TypeError("Nonce must be a byte string")
  114. self.nonce = nonce
  115. """Nonce"""
  116. self._factory = factory
  117. self._key = key
  118. self._tag = None # Cache for MAC tag
  119. self._mac_len = mac_len
  120. if not (4 <= mac_len <= 16):
  121. raise ValueError("Parameter 'mac_len' must be in the range 4..16")
  122. # Allowed transitions after initialization
  123. self._next = [self.update, self.encrypt, self.decrypt,
  124. self.digest, self.verify]
  125. self._no_more_assoc_data = False
  126. # Length of associated data
  127. self._auth_len = 0
  128. # Length of the ciphertext or plaintext
  129. self._msg_len = 0
  130. # Step 1 in SP800-38D, Algorithm 4 (encryption) - Compute H
  131. # See also Algorithm 5 (decryption)
  132. hash_subkey = factory.new(key,
  133. self._factory.MODE_ECB,
  134. **cipher_params
  135. ).encrypt(bchr(0) * 16)
  136. # Step 2 - Compute J0 (integer, not byte string!)
  137. if len(nonce) == 12:
  138. self._j0 = bytes_to_long(nonce + b("\x00\x00\x00\x01"))
  139. else:
  140. fill = (16 - (len(nonce) % 16)) % 16 + 8
  141. ghash_in = (nonce +
  142. bchr(0) * fill +
  143. long_to_bytes(8 * len(nonce), 8))
  144. self._j0 = bytes_to_long(_GHASH(hash_subkey)
  145. .update(ghash_in)
  146. .digest())
  147. # Step 3 - Prepare GCTR cipher for encryption/decryption
  148. self._cipher = factory.new(key,
  149. self._factory.MODE_CTR,
  150. initial_value=self._j0 + 1,
  151. nonce=b(""),
  152. **cipher_params)
  153. # Step 5 - Bootstrat GHASH
  154. self._signer = _GHASH(hash_subkey)
  155. # Step 6 - Prepare GCTR cipher for GMAC
  156. self._tag_cipher = factory.new(key,
  157. self._factory.MODE_CTR,
  158. initial_value=self._j0,
  159. nonce=b(""),
  160. **cipher_params)
  161. # Cache for data to authenticate
  162. self._cache = b("")
  163. self._status = MacStatus.PROCESSING_AUTH_DATA
  164. def update(self, assoc_data):
  165. """Protect associated data
  166. If there is any associated data, the caller has to invoke
  167. this function one or more times, before using
  168. ``decrypt`` or ``encrypt``.
  169. By *associated data* it is meant any data (e.g. packet headers) that
  170. will not be encrypted and will be transmitted in the clear.
  171. However, the receiver is still able to detect any modification to it.
  172. In GCM, the *associated data* is also called
  173. *additional authenticated data* (AAD).
  174. If there is no associated data, this method must not be called.
  175. The caller may split associated data in segments of any size, and
  176. invoke this method multiple times, each time with the next segment.
  177. :Parameters:
  178. assoc_data : byte string
  179. A piece of associated data. There are no restrictions on its size.
  180. """
  181. if self.update not in self._next:
  182. raise TypeError("update() can only be called"
  183. " immediately after initialization")
  184. self._next = [self.update, self.encrypt, self.decrypt,
  185. self.digest, self.verify]
  186. self._update(assoc_data)
  187. self._auth_len += len(assoc_data)
  188. return self
  189. def _update(self, data):
  190. assert(len(self._cache) < 16)
  191. if len(self._cache) > 0:
  192. filler = min(16 - len(self._cache), len(data))
  193. self._cache += data[:filler]
  194. data = data[filler:]
  195. if len(self._cache) < 16:
  196. return
  197. # The cache is exactly one block
  198. self._signer.update(self._cache)
  199. self._cache = b("")
  200. update_len = len(data) // 16 * 16
  201. self._cache = data[update_len:]
  202. if update_len > 0:
  203. self._signer.update(data[:update_len])
  204. def _pad_cache_and_update(self):
  205. assert(len(self._cache) < 16)
  206. # The authenticated data A is concatenated to the minimum
  207. # number of zero bytes (possibly none) such that the
  208. # - ciphertext C is aligned to the 16 byte boundary.
  209. # See step 5 in section 7.1
  210. # - ciphertext C is aligned to the 16 byte boundary.
  211. # See step 6 in section 7.2
  212. len_cache = len(self._cache)
  213. if len_cache > 0:
  214. self._update(bchr(0) * (16 - len_cache))
  215. def encrypt(self, plaintext):
  216. """Encrypt data with the key and the parameters set at initialization.
  217. A cipher object is stateful: once you have encrypted a message
  218. you cannot encrypt (or decrypt) another message using the same
  219. object.
  220. The data to encrypt can be broken up in two or
  221. more pieces and `encrypt` can be called multiple times.
  222. That is, the statement:
  223. >>> c.encrypt(a) + c.encrypt(b)
  224. is equivalent to:
  225. >>> c.encrypt(a+b)
  226. This function does not add any padding to the plaintext.
  227. :Parameters:
  228. plaintext : byte string
  229. The piece of data to encrypt.
  230. It can be of any length.
  231. :Return:
  232. the encrypted data, as a byte string.
  233. It is as long as *plaintext*.
  234. """
  235. if self.encrypt not in self._next:
  236. raise TypeError("encrypt() can only be called after"
  237. " initialization or an update()")
  238. self._next = [self.encrypt, self.digest]
  239. ciphertext = self._cipher.encrypt(plaintext)
  240. if self._status == MacStatus.PROCESSING_AUTH_DATA:
  241. self._pad_cache_and_update()
  242. self._status = MacStatus.PROCESSING_CIPHERTEXT
  243. self._update(ciphertext)
  244. self._msg_len += len(plaintext)
  245. return ciphertext
  246. def decrypt(self, ciphertext):
  247. """Decrypt data with the key and the parameters set at initialization.
  248. A cipher object is stateful: once you have decrypted a message
  249. you cannot decrypt (or encrypt) another message with the same
  250. object.
  251. The data to decrypt can be broken up in two or
  252. more pieces and `decrypt` can be called multiple times.
  253. That is, the statement:
  254. >>> c.decrypt(a) + c.decrypt(b)
  255. is equivalent to:
  256. >>> c.decrypt(a+b)
  257. This function does not remove any padding from the plaintext.
  258. :Parameters:
  259. ciphertext : byte string
  260. The piece of data to decrypt.
  261. It can be of any length.
  262. :Return: the decrypted data (byte string).
  263. """
  264. if self.decrypt not in self._next:
  265. raise TypeError("decrypt() can only be called"
  266. " after initialization or an update()")
  267. self._next = [self.decrypt, self.verify]
  268. if self._status == MacStatus.PROCESSING_AUTH_DATA:
  269. self._pad_cache_and_update()
  270. self._status = MacStatus.PROCESSING_CIPHERTEXT
  271. self._update(ciphertext)
  272. self._msg_len += len(ciphertext)
  273. return self._cipher.decrypt(ciphertext)
  274. def digest(self):
  275. """Compute the *binary* MAC tag in an AEAD mode.
  276. The caller invokes this function at the very end.
  277. This method returns the MAC that shall be sent to the receiver,
  278. together with the ciphertext.
  279. :Return: the MAC, as a byte string.
  280. """
  281. if self.digest not in self._next:
  282. raise TypeError("digest() cannot be called when decrypting"
  283. " or validating a message")
  284. self._next = [self.digest]
  285. return self._compute_mac()
  286. def _compute_mac(self):
  287. """Compute MAC without any FSM checks."""
  288. if self._tag:
  289. return self._tag
  290. # Step 5 in NIST SP 800-38D, Algorithm 4 - Compute S
  291. self._pad_cache_and_update()
  292. self._update(long_to_bytes(8 * self._auth_len, 8))
  293. self._update(long_to_bytes(8 * self._msg_len, 8))
  294. s_tag = self._signer.digest()
  295. # Step 6 - Compute T
  296. self._tag = self._tag_cipher.encrypt(s_tag)[:self._mac_len]
  297. return self._tag
  298. def hexdigest(self):
  299. """Compute the *printable* MAC tag.
  300. This method is like `digest`.
  301. :Return: the MAC, as a hexadecimal string.
  302. """
  303. return "".join(["%02x" % bord(x) for x in self.digest()])
  304. def verify(self, received_mac_tag):
  305. """Validate the *binary* MAC tag.
  306. The caller invokes this function at the very end.
  307. This method checks if the decrypted message is indeed valid
  308. (that is, if the key is correct) and it has not been
  309. tampered with while in transit.
  310. :Parameters:
  311. received_mac_tag : byte string
  312. This is the *binary* MAC, as received from the sender.
  313. :Raises ValueError:
  314. if the MAC does not match. The message has been tampered with
  315. or the key is incorrect.
  316. """
  317. if self.verify not in self._next:
  318. raise TypeError("verify() cannot be called"
  319. " when encrypting a message")
  320. self._next = [self.verify]
  321. secret = get_random_bytes(16)
  322. mac1 = BLAKE2s.new(digest_bits=160, key=secret,
  323. data=self._compute_mac())
  324. mac2 = BLAKE2s.new(digest_bits=160, key=secret,
  325. data=received_mac_tag)
  326. if mac1.digest() != mac2.digest():
  327. raise ValueError("MAC check failed")
  328. def hexverify(self, hex_mac_tag):
  329. """Validate the *printable* MAC tag.
  330. This method is like `verify`.
  331. :Parameters:
  332. hex_mac_tag : string
  333. This is the *printable* MAC, as received from the sender.
  334. :Raises ValueError:
  335. if the MAC does not match. The message has been tampered with
  336. or the key is incorrect.
  337. """
  338. self.verify(unhexlify(hex_mac_tag))
  339. def encrypt_and_digest(self, plaintext):
  340. """Perform encrypt() and digest() in one step.
  341. :Parameters:
  342. plaintext : byte string
  343. The piece of data to encrypt.
  344. :Return:
  345. a tuple with two byte strings:
  346. - the encrypted data
  347. - the MAC
  348. """
  349. return self.encrypt(plaintext), self.digest()
  350. def decrypt_and_verify(self, ciphertext, received_mac_tag):
  351. """Perform decrypt() and verify() in one step.
  352. :Parameters:
  353. ciphertext : byte string
  354. The piece of data to decrypt.
  355. received_mac_tag : byte string
  356. This is the *binary* MAC, as received from the sender.
  357. :Return: the decrypted data (byte string).
  358. :Raises ValueError:
  359. if the MAC does not match. The message has been tampered with
  360. or the key is incorrect.
  361. """
  362. plaintext = self.decrypt(ciphertext)
  363. self.verify(received_mac_tag)
  364. return plaintext
  365. def _create_gcm_cipher(factory, **kwargs):
  366. """Create a new block cipher, configured in Galois Counter Mode (GCM).
  367. :Parameters:
  368. factory : module
  369. A block cipher module, taken from `Crypto.Cipher`.
  370. The cipher must have block length of 16 bytes.
  371. GCM has been only defined for `Crypto.Cipher.AES`.
  372. :Keywords:
  373. key : byte string
  374. The secret key to use in the symmetric cipher.
  375. It must be 16 (e.g. *AES-128*), 24 (e.g. *AES-192*)
  376. or 32 (e.g. *AES-256*) bytes long.
  377. nonce : byte string
  378. A value that must never be reused for any other encryption.
  379. There are no restrictions on its length,
  380. but it is recommended to use at least 16 bytes.
  381. The nonce shall never repeat for two
  382. different messages encrypted with the same key,
  383. but it does not need to be random.
  384. If not provided, a 16 byte nonce will be randomly created.
  385. mac_len : integer
  386. Length of the MAC, in bytes.
  387. It must be no larger than 16 bytes (which is the default).
  388. """
  389. try:
  390. key = kwargs.pop("key")
  391. except KeyError, e:
  392. raise TypeError("Missing parameter:" + str(e))
  393. nonce = kwargs.pop("nonce", None)
  394. if nonce is None:
  395. nonce = get_random_bytes(16)
  396. mac_len = kwargs.pop("mac_len", 16)
  397. return GcmMode(factory, key, nonce, mac_len, kwargs)