ChaCha20.py 11 KB

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