_mode_siv.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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. Synthetic Initialization Vector (SIV) mode.
  32. """
  33. __all__ = ['SivMode']
  34. from binascii import hexlify
  35. from Crypto.Util.py3compat import byte_string, bord, unhexlify, b
  36. from Crypto.Util.number import long_to_bytes, bytes_to_long
  37. from Crypto.Protocol.KDF import _S2V
  38. from Crypto.Hash import BLAKE2s
  39. from Crypto.Random import get_random_bytes
  40. class SivMode(object):
  41. """Synthetic Initialization Vector (SIV).
  42. This is an Authenticated Encryption with Associated Data (`AEAD`_) mode.
  43. It provides both confidentiality and authenticity.
  44. The header of the message may be left in the clear, if needed, and it will
  45. still be subject to authentication. The decryption step tells the receiver
  46. if the message comes from a source that really knowns the secret key.
  47. Additionally, decryption detects if any part of the message - including the
  48. header - has been modified or corrupted.
  49. Unlike other AEAD modes such as CCM, EAX or GCM, accidental reuse of a
  50. nonce is not catastrophic for the confidentiality of the message. The only
  51. effect is that an attacker can tell when the same plaintext (and same
  52. associated data) is protected with the same key.
  53. The length of the MAC is fixed to the block size of the underlying cipher.
  54. The key size is twice the length of the key of the underlying cipher.
  55. This mode is only available for AES ciphers.
  56. +--------------------+---------------+-------------------+
  57. | Cipher | SIV MAC size | SIV key length |
  58. | | (bytes) | (bytes) |
  59. +====================+===============+===================+
  60. | AES-128 | 16 | 32 |
  61. +--------------------+---------------+-------------------+
  62. | AES-192 | 16 | 48 |
  63. +--------------------+---------------+-------------------+
  64. | AES-256 | 16 | 64 |
  65. +--------------------+---------------+-------------------+
  66. See `RFC5297`_ and the `original paper`__.
  67. .. _RFC5297: https://tools.ietf.org/html/rfc5297
  68. .. _AEAD: http://blog.cryptographyengineering.com/2012/05/how-to-choose-authenticated-encryption.html
  69. .. __: http://www.cs.ucdavis.edu/~rogaway/papers/keywrap.pdf
  70. :undocumented: __init__
  71. """
  72. def __init__(self, factory, key, nonce, kwargs):
  73. self.block_size = factory.block_size
  74. """The block size of the underlying cipher, in bytes."""
  75. self._factory = factory
  76. self._nonce = nonce
  77. self._cipher_params = kwargs
  78. if len(key) not in (32, 48, 64):
  79. raise ValueError("Incorrect key length (%d bytes)" % len(key))
  80. if nonce is not None:
  81. if not byte_string(nonce):
  82. raise TypeError("When provided, the nonce must be a byte string")
  83. if len(nonce) == 0:
  84. raise ValueError("When provided, the nonce must be non-empty")
  85. self.nonce = nonce
  86. """Public attribute is only available in case of non-deterministic
  87. encryption."""
  88. subkey_size = len(key) // 2
  89. self._mac_tag = None # Cache for MAC tag
  90. self._kdf = _S2V(key[:subkey_size],
  91. ciphermod=factory,
  92. cipher_params=self._cipher_params)
  93. self._subkey_cipher = key[subkey_size:]
  94. # Purely for the purpose of verifying that cipher_params are OK
  95. factory.new(key[:subkey_size], factory.MODE_ECB, **kwargs)
  96. # Allowed transitions after initialization
  97. self._next = [self.update, self.encrypt, self.decrypt,
  98. self.digest, self.verify]
  99. def _create_ctr_cipher(self, mac_tag):
  100. """Create a new CTR cipher from the MAC in SIV mode"""
  101. tag_int = bytes_to_long(mac_tag)
  102. return self._factory.new(
  103. self._subkey_cipher,
  104. self._factory.MODE_CTR,
  105. initial_value=tag_int ^ (tag_int & 0x8000000080000000L),
  106. nonce=b(""),
  107. **self._cipher_params)
  108. def update(self, component):
  109. """Protect one associated data component
  110. For SIV, the associated data is a sequence (*vector*) of non-empty
  111. byte strings (*components*).
  112. This method consumes the next component. It must be called
  113. once for each of the components that constitue the associated data.
  114. Note that the components have clear boundaries, so that:
  115. >>> cipher.update(b"builtin")
  116. >>> cipher.update(b"securely")
  117. is not equivalent to:
  118. >>> cipher.update(b"built")
  119. >>> cipher.update(b"insecurely")
  120. If there is no associated data, this method must not be called.
  121. :Parameters:
  122. component : byte string
  123. The next associated data component. It must not be empty.
  124. """
  125. if self.update not in self._next:
  126. raise TypeError("update() can only be called"
  127. " immediately after initialization")
  128. self._next = [self.update, self.encrypt, self.decrypt,
  129. self.digest, self.verify]
  130. return self._kdf.update(component)
  131. def encrypt(self, plaintext):
  132. """Encrypt data with the key and the parameters set at initialization.
  133. A cipher object is stateful: once you have encrypted a message
  134. you cannot encrypt (or decrypt) another message using the same
  135. object.
  136. This method can be called only **once**.
  137. You cannot reuse an object for encrypting
  138. or decrypting other data with the same key.
  139. This function does not add any padding to the plaintext.
  140. :Parameters:
  141. plaintext : byte string
  142. The piece of data to encrypt.
  143. It can be of any length, but it cannot be empty.
  144. :Return:
  145. the encrypted data, as a byte string.
  146. It is as long as *plaintext*.
  147. """
  148. if self.encrypt not in self._next:
  149. raise TypeError("encrypt() can only be called after"
  150. " initialization or an update()")
  151. self._next = [self.digest]
  152. if self._nonce:
  153. self._kdf.update(self.nonce)
  154. self._kdf.update(plaintext)
  155. self._mac_tag = self._kdf.derive()
  156. cipher = self._create_ctr_cipher(self._mac_tag)
  157. return cipher.encrypt(plaintext)
  158. def decrypt(self, ciphertext):
  159. """Decrypt data with the key and the parameters set at initialization.
  160. For SIV, decryption and verification must take place at the same
  161. point. This method shall not be used.
  162. Use `decrypt_and_verify` instead.
  163. """
  164. raise TypeError("decrypt() not allowed for SIV mode."
  165. " Use decrypt_and_verify() instead.")
  166. def digest(self):
  167. """Compute the *binary* MAC tag.
  168. The caller invokes this function at the very end.
  169. This method returns the MAC that shall be sent to the receiver,
  170. together with the ciphertext.
  171. :Return: the MAC, as a byte string.
  172. """
  173. if self.digest not in self._next:
  174. raise TypeError("digest() cannot be called when decrypting"
  175. " or validating a message")
  176. self._next = [self.digest]
  177. if self._mac_tag is None:
  178. self._mac_tag = self._kdf.derive()
  179. return self._mac_tag
  180. def hexdigest(self):
  181. """Compute the *printable* MAC tag.
  182. This method is like `digest`.
  183. :Return: the MAC, as a hexadecimal string.
  184. """
  185. return "".join(["%02x" % bord(x) for x in self.digest()])
  186. def verify(self, received_mac_tag):
  187. """Validate the *binary* MAC tag.
  188. The caller invokes this function at the very end.
  189. This method checks if the decrypted message is indeed valid
  190. (that is, if the key is correct) and it has not been
  191. tampered with while in transit.
  192. :Parameters:
  193. received_mac_tag : byte string
  194. This is the *binary* MAC, as received from the sender.
  195. :Raises ValueError:
  196. if the MAC does not match. The message has been tampered with
  197. or the key is incorrect.
  198. """
  199. if self.verify not in self._next:
  200. raise TypeError("verify() cannot be called"
  201. " when encrypting a message")
  202. self._next = [self.verify]
  203. if self._mac_tag is None:
  204. self._mac_tag = self._kdf.derive()
  205. secret = get_random_bytes(16)
  206. mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=self._mac_tag)
  207. mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=received_mac_tag)
  208. if mac1.digest() != mac2.digest():
  209. raise ValueError("MAC check failed")
  210. def hexverify(self, hex_mac_tag):
  211. """Validate the *printable* MAC tag.
  212. This method is like `verify`.
  213. :Parameters:
  214. hex_mac_tag : string
  215. This is the *printable* MAC, as received from the sender.
  216. :Raises ValueError:
  217. if the MAC does not match. The message has been tampered with
  218. or the key is incorrect.
  219. """
  220. self.verify(unhexlify(hex_mac_tag))
  221. def encrypt_and_digest(self, plaintext):
  222. """Perform encrypt() and digest() in one step.
  223. :Parameters:
  224. plaintext : byte string
  225. The piece of data to encrypt.
  226. :Return:
  227. a tuple with two byte strings:
  228. - the encrypted data
  229. - the MAC
  230. """
  231. return self.encrypt(plaintext), self.digest()
  232. def decrypt_and_verify(self, ciphertext, mac_tag):
  233. """Perform decryption and verification in one step.
  234. A cipher object is stateful: once you have decrypted a message
  235. you cannot decrypt (or encrypt) another message with the same
  236. object.
  237. You cannot reuse an object for encrypting
  238. or decrypting other data with the same key.
  239. This function does not remove any padding from the plaintext.
  240. :Parameters:
  241. ciphertext : byte string
  242. The piece of data to decrypt.
  243. It can be of any length.
  244. mac_tag : byte string
  245. This is the *binary* MAC, as received from the sender.
  246. :Return: the decrypted data (byte string).
  247. :Raises ValueError:
  248. if the MAC does not match. The message has been tampered with
  249. or the key is incorrect.
  250. """
  251. if self.decrypt not in self._next:
  252. raise TypeError("decrypt() can only be called"
  253. " after initialization or an update()")
  254. self._next = [self.verify]
  255. # Take the MAC and start the cipher for decryption
  256. self._cipher = self._create_ctr_cipher(mac_tag)
  257. plaintext = self._cipher.decrypt(ciphertext)
  258. if self._nonce:
  259. self._kdf.update(self.nonce)
  260. if plaintext:
  261. self._kdf.update(plaintext)
  262. self.verify(mac_tag)
  263. return plaintext
  264. def _create_siv_cipher(factory, **kwargs):
  265. """Create a new block cipher, configured in
  266. Synthetic Initializaton Vector (SIV) mode.
  267. :Parameters:
  268. factory : object
  269. A symmetric cipher module from `Crypto.Cipher`
  270. (like `Crypto.Cipher.AES`).
  271. :Keywords:
  272. key : byte string
  273. The secret key to use in the symmetric cipher.
  274. It must be 32, 48 or 64 bytes long.
  275. If AES is the chosen cipher, the variants *AES-128*,
  276. *AES-192* and or *AES-256* will be used internally.
  277. nonce : byte string
  278. For deterministic encryption, it is not present.
  279. Otherwise, it is a value that must never be reused
  280. for encrypting message under this key.
  281. There are no restrictions on its length,
  282. but it is recommended to use at least 16 bytes.
  283. """
  284. try:
  285. key = kwargs.pop("key")
  286. except KeyError, e:
  287. raise TypeError("Missing parameter: " + str(e))
  288. nonce = kwargs.pop("nonce", None)
  289. return SivMode(factory, key, nonce, kwargs)