ChaCha20_Poly1305.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. # ===================================================================
  2. #
  3. # Copyright (c) 2018, Helder Eijs <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 binascii import unhexlify
  31. from tls.Crypto.Cipher import ChaCha20
  32. from tls.Crypto.Cipher.ChaCha20 import _HChaCha20
  33. from tls.Crypto.Hash import Poly1305, BLAKE2s
  34. from tls.Crypto.Random import get_random_bytes
  35. from tls.Crypto.Util.number import long_to_bytes
  36. from tls.Crypto.Util.py3compat import _copy_bytes, bord
  37. from tls.Crypto.Util._raw_api import is_buffer
  38. def _enum(**enums):
  39. return type('Enum', (), enums)
  40. _CipherStatus = _enum(PROCESSING_AUTH_DATA=1,
  41. PROCESSING_CIPHERTEXT=2,
  42. PROCESSING_DONE=3)
  43. class ChaCha20Poly1305Cipher(object):
  44. """ChaCha20-Poly1305 and XChaCha20-Poly1305 cipher object.
  45. Do not create it directly. Use :py:func:`new` instead.
  46. :var nonce: The nonce with length 8, 12 or 24 bytes
  47. :vartype nonce: byte string
  48. """
  49. def __init__(self, key, nonce):
  50. """Initialize a ChaCha20-Poly1305 AEAD cipher object
  51. See also `new()` at the module level."""
  52. self.nonce = _copy_bytes(None, None, nonce)
  53. self._next = (self.update, self.encrypt, self.decrypt, self.digest,
  54. self.verify)
  55. self._authenticator = Poly1305.new(key=key, nonce=nonce, cipher=ChaCha20)
  56. self._cipher = ChaCha20.new(key=key, nonce=nonce)
  57. self._cipher.seek(64) # Block counter starts at 1
  58. self._len_aad = 0
  59. self._len_ct = 0
  60. self._mac_tag = None
  61. self._status = _CipherStatus.PROCESSING_AUTH_DATA
  62. def update(self, data):
  63. """Protect the associated data.
  64. Associated data (also known as *additional authenticated data* - AAD)
  65. is the piece of the message that must stay in the clear, while
  66. still allowing the receiver to verify its integrity.
  67. An example is packet headers.
  68. The associated data (possibly split into multiple segments) is
  69. fed into :meth:`update` before any call to :meth:`decrypt` or :meth:`encrypt`.
  70. If there is no associated data, :meth:`update` is not called.
  71. :param bytes/bytearray/memoryview assoc_data:
  72. A piece of associated data. There are no restrictions on its size.
  73. """
  74. if self.update not in self._next:
  75. raise TypeError("update() method cannot be called")
  76. self._len_aad += len(data)
  77. self._authenticator.update(data)
  78. def _pad_aad(self):
  79. assert(self._status == _CipherStatus.PROCESSING_AUTH_DATA)
  80. if self._len_aad & 0x0F:
  81. self._authenticator.update(b'\x00' * (16 - (self._len_aad & 0x0F)))
  82. self._status = _CipherStatus.PROCESSING_CIPHERTEXT
  83. def encrypt(self, plaintext, output=None):
  84. """Encrypt a piece of data.
  85. Args:
  86. plaintext(bytes/bytearray/memoryview): The data to encrypt, of any size.
  87. Keyword Args:
  88. output(bytes/bytearray/memoryview): The location where the ciphertext
  89. is written to. If ``None``, the ciphertext is returned.
  90. Returns:
  91. If ``output`` is ``None``, the ciphertext is returned as ``bytes``.
  92. Otherwise, ``None``.
  93. """
  94. if self.encrypt not in self._next:
  95. raise TypeError("encrypt() method cannot be called")
  96. if self._status == _CipherStatus.PROCESSING_AUTH_DATA:
  97. self._pad_aad()
  98. self._next = (self.encrypt, self.digest)
  99. result = self._cipher.encrypt(plaintext, output=output)
  100. self._len_ct += len(plaintext)
  101. if output is None:
  102. self._authenticator.update(result)
  103. else:
  104. self._authenticator.update(output)
  105. return result
  106. def decrypt(self, ciphertext, output=None):
  107. """Decrypt a piece of data.
  108. Args:
  109. ciphertext(bytes/bytearray/memoryview): The data to decrypt, of any size.
  110. Keyword Args:
  111. output(bytes/bytearray/memoryview): The location where the plaintext
  112. is written to. If ``None``, the plaintext is returned.
  113. Returns:
  114. If ``output`` is ``None``, the plaintext is returned as ``bytes``.
  115. Otherwise, ``None``.
  116. """
  117. if self.decrypt not in self._next:
  118. raise TypeError("decrypt() method cannot be called")
  119. if self._status == _CipherStatus.PROCESSING_AUTH_DATA:
  120. self._pad_aad()
  121. self._next = (self.decrypt, self.verify)
  122. self._len_ct += len(ciphertext)
  123. self._authenticator.update(ciphertext)
  124. return self._cipher.decrypt(ciphertext, output=output)
  125. def _compute_mac(self):
  126. """Finalize the cipher (if not done already) and return the MAC."""
  127. if self._mac_tag:
  128. assert(self._status == _CipherStatus.PROCESSING_DONE)
  129. return self._mac_tag
  130. assert(self._status != _CipherStatus.PROCESSING_DONE)
  131. if self._status == _CipherStatus.PROCESSING_AUTH_DATA:
  132. self._pad_aad()
  133. if self._len_ct & 0x0F:
  134. self._authenticator.update(b'\x00' * (16 - (self._len_ct & 0x0F)))
  135. self._status = _CipherStatus.PROCESSING_DONE
  136. self._authenticator.update(long_to_bytes(self._len_aad, 8)[::-1])
  137. self._authenticator.update(long_to_bytes(self._len_ct, 8)[::-1])
  138. self._mac_tag = self._authenticator.digest()
  139. return self._mac_tag
  140. def digest(self):
  141. """Compute the *binary* authentication tag (MAC).
  142. :Return: the MAC tag, as 16 ``bytes``.
  143. """
  144. if self.digest not in self._next:
  145. raise TypeError("digest() method cannot be called")
  146. self._next = (self.digest,)
  147. return self._compute_mac()
  148. def hexdigest(self):
  149. """Compute the *printable* authentication tag (MAC).
  150. This method is like :meth:`digest`.
  151. :Return: the MAC tag, as a hexadecimal string.
  152. """
  153. return "".join(["%02x" % bord(x) for x in self.digest()])
  154. def verify(self, received_mac_tag):
  155. """Validate the *binary* authentication tag (MAC).
  156. The receiver invokes this method at the very end, to
  157. check if the associated data (if any) and the decrypted
  158. messages are valid.
  159. :param bytes/bytearray/memoryview received_mac_tag:
  160. This is the 16-byte *binary* MAC, as received from the sender.
  161. :Raises ValueError:
  162. if the MAC does not match. The message has been tampered with
  163. or the key is incorrect.
  164. """
  165. if self.verify not in self._next:
  166. raise TypeError("verify() cannot be called"
  167. " when encrypting a message")
  168. self._next = (self.verify,)
  169. secret = get_random_bytes(16)
  170. self._compute_mac()
  171. mac1 = BLAKE2s.new(digest_bits=160, key=secret,
  172. data=self._mac_tag)
  173. mac2 = BLAKE2s.new(digest_bits=160, key=secret,
  174. data=received_mac_tag)
  175. if mac1.digest() != mac2.digest():
  176. raise ValueError("MAC check failed")
  177. def hexverify(self, hex_mac_tag):
  178. """Validate the *printable* authentication tag (MAC).
  179. This method is like :meth:`verify`.
  180. :param string hex_mac_tag:
  181. This is the *printable* MAC.
  182. :Raises ValueError:
  183. if the MAC does not match. The message has been tampered with
  184. or the key is incorrect.
  185. """
  186. self.verify(unhexlify(hex_mac_tag))
  187. def encrypt_and_digest(self, plaintext):
  188. """Perform :meth:`encrypt` and :meth:`digest` in one step.
  189. :param plaintext: The data to encrypt, of any size.
  190. :type plaintext: bytes/bytearray/memoryview
  191. :return: a tuple with two ``bytes`` objects:
  192. - the ciphertext, of equal length as the plaintext
  193. - the 16-byte MAC tag
  194. """
  195. return self.encrypt(plaintext), self.digest()
  196. def decrypt_and_verify(self, ciphertext, received_mac_tag):
  197. """Perform :meth:`decrypt` and :meth:`verify` in one step.
  198. :param ciphertext: The piece of data to decrypt.
  199. :type ciphertext: bytes/bytearray/memoryview
  200. :param bytes received_mac_tag:
  201. This is the 16-byte *binary* MAC, as received from the sender.
  202. :return: the decrypted data (as ``bytes``)
  203. :raises ValueError:
  204. if the MAC does not match. The message has been tampered with
  205. or the key is incorrect.
  206. """
  207. plaintext = self.decrypt(ciphertext)
  208. self.verify(received_mac_tag)
  209. return plaintext
  210. def new(**kwargs):
  211. """Create a new ChaCha20-Poly1305 or XChaCha20-Poly1305 AEAD cipher.
  212. :keyword key: The secret key to use. It must be 32 bytes long.
  213. :type key: byte string
  214. :keyword nonce:
  215. A value that must never be reused for any other encryption
  216. done with this key.
  217. For ChaCha20-Poly1305, it must be 8 or 12 bytes long.
  218. For XChaCha20-Poly1305, it must be 24 bytes long.
  219. If not provided, 12 ``bytes`` will be generated randomly
  220. (you can find them back in the ``nonce`` attribute).
  221. :type nonce: bytes, bytearray, memoryview
  222. :Return: a :class:`Crypto.Cipher.ChaCha20.ChaCha20Poly1305Cipher` object
  223. """
  224. try:
  225. key = kwargs.pop("key")
  226. except KeyError as e:
  227. raise TypeError("Missing parameter %s" % e)
  228. self._len_ct += len(plaintext)
  229. if len(key) != 32:
  230. raise ValueError("Key must be 32 bytes long")
  231. nonce = kwargs.pop("nonce", None)
  232. if nonce is None:
  233. nonce = get_random_bytes(12)
  234. if len(nonce) in (8, 12):
  235. pass
  236. elif len(nonce) == 24:
  237. key = _HChaCha20(key, nonce[:16])
  238. nonce = b'\x00\x00\x00\x00' + nonce[16:]
  239. else:
  240. raise ValueError("Nonce must be 8, 12 or 24 bytes long")
  241. if not is_buffer(nonce):
  242. raise TypeError("nonce must be bytes, bytearray or memoryview")
  243. if kwargs:
  244. raise TypeError("Unknown parameters: " + str(kwargs))
  245. return ChaCha20Poly1305Cipher(key, nonce)
  246. # Size of a key (in bytes)
  247. key_size = 32