ChaCha20_Poly1305.py 11 KB

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