ChaCha20.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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. from tls.Crypto.Random import get_random_bytes
  31. from tls.Crypto.Util.py3compat import _copy_bytes
  32. from tls.Crypto.Util._raw_api import (load_pycryptodome_raw_lib,
  33. create_string_buffer,
  34. get_raw_buffer, VoidPointer,
  35. SmartPointer, c_size_t,
  36. c_uint8_ptr, c_ulong,
  37. is_writeable_buffer)
  38. _raw_chacha20_lib = load_pycryptodome_raw_lib("Crypto.Cipher._chacha20",
  39. """
  40. int chacha20_init(void **pState,
  41. const uint8_t *key,
  42. size_t keySize,
  43. const uint8_t *nonce,
  44. size_t nonceSize);
  45. int chacha20_destroy(void *state);
  46. int chacha20_encrypt(void *state,
  47. const uint8_t in[],
  48. uint8_t out[],
  49. size_t len);
  50. int chacha20_seek(void *state,
  51. unsigned long block_high,
  52. unsigned long block_low,
  53. unsigned offset);
  54. int hchacha20( const uint8_t key[32],
  55. const uint8_t nonce16[16],
  56. uint8_t subkey[32]);
  57. """)
  58. def _HChaCha20(key, nonce):
  59. assert(len(key) == 32)
  60. assert(len(nonce) == 16)
  61. subkey = bytearray(32)
  62. result = _raw_chacha20_lib.hchacha20(
  63. c_uint8_ptr(key),
  64. c_uint8_ptr(nonce),
  65. c_uint8_ptr(subkey))
  66. if result:
  67. raise ValueError("Error %d when deriving subkey with HChaCha20" % result)
  68. return subkey
  69. class ChaCha20Cipher(object):
  70. """ChaCha20 (or XChaCha20) cipher object.
  71. Do not create it directly. Use :py:func:`new` instead.
  72. :var nonce: The nonce with length 8, 12 or 24 bytes
  73. :vartype nonce: bytes
  74. """
  75. block_size = 1
  76. def __init__(self, key, nonce):
  77. """Initialize a ChaCha20/XChaCha20 cipher object
  78. See also `new()` at the module level."""
  79. # XChaCha20 requires a key derivation with HChaCha20
  80. # See 2.3 in https://tools.ietf.org/html/draft-arciszewski-xchacha-03
  81. if len(nonce) == 24:
  82. key = _HChaCha20(key, nonce[:16])
  83. nonce = b'\x00' * 4 + nonce[16:]
  84. self._name = "XChaCha20"
  85. else:
  86. self._name = "ChaCha20"
  87. self.nonce = _copy_bytes(None, None, nonce)
  88. self._next = ( self.encrypt, self.decrypt )
  89. self._state = VoidPointer()
  90. result = _raw_chacha20_lib.chacha20_init(
  91. self._state.address_of(),
  92. c_uint8_ptr(key),
  93. c_size_t(len(key)),
  94. self.nonce,
  95. c_size_t(len(nonce)))
  96. if result:
  97. raise ValueError("Error %d instantiating a %s cipher" % (result,
  98. self._name))
  99. self._state = SmartPointer(self._state.get(),
  100. _raw_chacha20_lib.chacha20_destroy)
  101. def encrypt(self, plaintext, output=None):
  102. """Encrypt a piece of data.
  103. Args:
  104. plaintext(bytes/bytearray/memoryview): The data to encrypt, of any size.
  105. Keyword Args:
  106. output(bytes/bytearray/memoryview): The location where the ciphertext
  107. is written to. If ``None``, the ciphertext is returned.
  108. Returns:
  109. If ``output`` is ``None``, the ciphertext is returned as ``bytes``.
  110. Otherwise, ``None``.
  111. """
  112. if self.encrypt not in self._next:
  113. raise TypeError("Cipher object can only be used for decryption")
  114. self._next = ( self.encrypt, )
  115. return self._encrypt(plaintext, output)
  116. def _encrypt(self, plaintext, output):
  117. """Encrypt without FSM checks"""
  118. if output is None:
  119. ciphertext = create_string_buffer(len(plaintext))
  120. else:
  121. ciphertext = output
  122. if not is_writeable_buffer(output):
  123. raise TypeError("output must be a bytearray or a writeable memoryview")
  124. if len(plaintext) != len(output):
  125. raise ValueError("output must have the same length as the input"
  126. " (%d bytes)" % len(plaintext))
  127. result = _raw_chacha20_lib.chacha20_encrypt(
  128. self._state.get(),
  129. c_uint8_ptr(plaintext),
  130. c_uint8_ptr(ciphertext),
  131. c_size_t(len(plaintext)))
  132. if result:
  133. raise ValueError("Error %d while encrypting with %s" % (result, self._name))
  134. if output is None:
  135. return get_raw_buffer(ciphertext)
  136. else:
  137. return None
  138. def decrypt(self, ciphertext, output=None):
  139. """Decrypt a piece of data.
  140. Args:
  141. ciphertext(bytes/bytearray/memoryview): The data to decrypt, of any size.
  142. Keyword Args:
  143. output(bytes/bytearray/memoryview): The location where the plaintext
  144. is written to. If ``None``, the plaintext is returned.
  145. Returns:
  146. If ``output`` is ``None``, the plaintext is returned as ``bytes``.
  147. Otherwise, ``None``.
  148. """
  149. if self.decrypt not in self._next:
  150. raise TypeError("Cipher object can only be used for encryption")
  151. self._next = ( self.decrypt, )
  152. try:
  153. return self._encrypt(ciphertext, output)
  154. except ValueError as e:
  155. raise ValueError(str(e).replace("enc", "dec"))
  156. def seek(self, position):
  157. """Seek to a certain position in the key stream.
  158. Args:
  159. position (integer):
  160. The absolute position within the key stream, in bytes.
  161. """
  162. position, offset = divmod(position, 64)
  163. block_low = position & 0xFFFFFFFF
  164. block_high = position >> 32
  165. result = _raw_chacha20_lib.chacha20_seek(
  166. self._state.get(),
  167. c_ulong(block_high),
  168. c_ulong(block_low),
  169. offset
  170. )
  171. if result:
  172. raise ValueError("Error %d while seeking with %s" % (result, self._name))
  173. def _derive_Poly1305_key_pair(key, nonce):
  174. """Derive a tuple (r, s, nonce) for a Poly1305 MAC.
  175. If nonce is ``None``, a new 12-byte nonce is generated.
  176. """
  177. if len(key) != 32:
  178. raise ValueError("Poly1305 with ChaCha20 requires a 32-byte key")
  179. if nonce is None:
  180. padded_nonce = nonce = get_random_bytes(12)
  181. elif len(nonce) == 8:
  182. # See RFC7538, 2.6: [...] ChaCha20 as specified here requires a 96-bit
  183. # nonce. So if the provided nonce is only 64-bit, then the first 32
  184. # bits of the nonce will be set to a constant number.
  185. # This will usually be zero, but for protocols with multiple senders it may be
  186. # different for each sender, but should be the same for all
  187. # invocations of the function with the same key by a particular
  188. # sender.
  189. padded_nonce = b'\x00\x00\x00\x00' + nonce
  190. elif len(nonce) == 12:
  191. padded_nonce = nonce
  192. else:
  193. raise ValueError("Poly1305 with ChaCha20 requires an 8- or 12-byte nonce")
  194. rs = new(key=key, nonce=padded_nonce).encrypt(b'\x00' * 32)
  195. return rs[:16], rs[16:], nonce
  196. def new(**kwargs):
  197. """Create a new ChaCha20 or XChaCha20 cipher
  198. Keyword Args:
  199. key (bytes/bytearray/memoryview): The secret key to use.
  200. It must be 32 bytes long.
  201. nonce (bytes/bytearray/memoryview): A mandatory value that
  202. must never be reused for any other encryption
  203. done with this key.
  204. For ChaCha20, it must be 8 or 12 bytes long.
  205. For XChaCha20, it must be 24 bytes long.
  206. If not provided, 8 bytes will be randomly generated
  207. (you can find them back in the ``nonce`` attribute).
  208. :Return: a :class:`Crypto.Cipher.ChaCha20.ChaCha20Cipher` object
  209. """
  210. try:
  211. key = kwargs.pop("key")
  212. except KeyError as e:
  213. raise TypeError("Missing parameter %s" % e)
  214. nonce = kwargs.pop("nonce", None)
  215. if nonce is None:
  216. nonce = get_random_bytes(8)
  217. if len(key) != 32:
  218. raise ValueError("ChaCha20/XChaCha20 key must be 32 bytes long")
  219. if len(nonce) not in (8, 12, 24):
  220. raise ValueError("Nonce must be 8/12 bytes(ChaCha20) or 24 bytes (XChaCha20)")
  221. if kwargs:
  222. raise TypeError("Unknown parameters: " + str(kwargs))
  223. return ChaCha20Cipher(key, nonce)
  224. # Size of a data block (in bytes)
  225. block_size = 1
  226. # Size of a key (in bytes)
  227. key_size = 32