_mode_ctr.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Cipher/mode_ctr.py : CTR mode
  4. #
  5. # ===================================================================
  6. # The contents of this file are dedicated to the public domain. To
  7. # the extent that dedication to the public domain is not available,
  8. # everyone is granted a worldwide, perpetual, royalty-free,
  9. # non-exclusive license to exercise all rights associated with the
  10. # contents of this file for any purpose whatsoever.
  11. # No rights are reserved.
  12. #
  13. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  14. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  15. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  16. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  17. # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  18. # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  19. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. # SOFTWARE.
  21. # ===================================================================
  22. """
  23. Counter (CTR) mode.
  24. """
  25. __all__ = ['CtrMode']
  26. import struct
  27. from tls.Crypto.Util._raw_api import (load_pycryptodome_raw_lib, VoidPointer,
  28. create_string_buffer, get_raw_buffer,
  29. SmartPointer, c_size_t, c_uint8_ptr,
  30. is_writeable_buffer)
  31. from tls.Crypto.Random import get_random_bytes
  32. from tls.Crypto.Util.py3compat import _copy_bytes, is_native_int
  33. from tls.Crypto.Util.number import long_to_bytes
  34. raw_ctr_lib = load_pycryptodome_raw_lib("Crypto.Cipher._raw_ctr", """
  35. int CTR_start_operation(void *cipher,
  36. uint8_t initialCounterBlock[],
  37. size_t initialCounterBlock_len,
  38. size_t prefix_len,
  39. unsigned counter_len,
  40. unsigned littleEndian,
  41. void **pResult);
  42. int CTR_encrypt(void *ctrState,
  43. const uint8_t *in,
  44. uint8_t *out,
  45. size_t data_len);
  46. int CTR_decrypt(void *ctrState,
  47. const uint8_t *in,
  48. uint8_t *out,
  49. size_t data_len);
  50. int CTR_stop_operation(void *ctrState);"""
  51. )
  52. class CtrMode(object):
  53. """*CounTeR (CTR)* mode.
  54. This mode is very similar to ECB, in that
  55. encryption of one block is done independently of all other blocks.
  56. Unlike ECB, the block *position* contributes to the encryption
  57. and no information leaks about symbol frequency.
  58. Each message block is associated to a *counter* which
  59. must be unique across all messages that get encrypted
  60. with the same key (not just within the same message).
  61. The counter is as big as the block size.
  62. Counters can be generated in several ways. The most
  63. straightword one is to choose an *initial counter block*
  64. (which can be made public, similarly to the *IV* for the
  65. other modes) and increment its lowest **m** bits by one
  66. (modulo *2^m*) for each block. In most cases, **m** is
  67. chosen to be half the block size.
  68. See `NIST SP800-38A`_, Section 6.5 (for the mode) and
  69. Appendix B (for how to manage the *initial counter block*).
  70. .. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf
  71. :undocumented: __init__
  72. """
  73. def __init__(self, block_cipher, initial_counter_block,
  74. prefix_len, counter_len, little_endian):
  75. """Create a new block cipher, configured in CTR mode.
  76. :Parameters:
  77. block_cipher : C pointer
  78. A smart pointer to the low-level block cipher instance.
  79. initial_counter_block : bytes/bytearray/memoryview
  80. The initial plaintext to use to generate the key stream.
  81. It is as large as the cipher block, and it embeds
  82. the initial value of the counter.
  83. This value must not be reused.
  84. It shall contain a nonce or a random component.
  85. Reusing the *initial counter block* for encryptions
  86. performed with the same key compromises confidentiality.
  87. prefix_len : integer
  88. The amount of bytes at the beginning of the counter block
  89. that never change.
  90. counter_len : integer
  91. The length in bytes of the counter embedded in the counter
  92. block.
  93. little_endian : boolean
  94. True if the counter in the counter block is an integer encoded
  95. in little endian mode. If False, it is big endian.
  96. """
  97. if len(initial_counter_block) == prefix_len + counter_len:
  98. self.nonce = _copy_bytes(None, prefix_len, initial_counter_block)
  99. """Nonce; not available if there is a fixed suffix"""
  100. self._state = VoidPointer()
  101. result = raw_ctr_lib.CTR_start_operation(block_cipher.get(),
  102. c_uint8_ptr(initial_counter_block),
  103. c_size_t(len(initial_counter_block)),
  104. c_size_t(prefix_len),
  105. counter_len,
  106. little_endian,
  107. self._state.address_of())
  108. if result:
  109. raise ValueError("Error %X while instantiating the CTR mode"
  110. % result)
  111. # Ensure that object disposal of this Python object will (eventually)
  112. # free the memory allocated by the raw library for the cipher mode
  113. self._state = SmartPointer(self._state.get(),
  114. raw_ctr_lib.CTR_stop_operation)
  115. # Memory allocated for the underlying block cipher is now owed
  116. # by the cipher mode
  117. block_cipher.release()
  118. self.block_size = len(initial_counter_block)
  119. """The block size of the underlying cipher, in bytes."""
  120. self._next = [self.encrypt, self.decrypt]
  121. def encrypt(self, plaintext, output=None):
  122. """Encrypt data with the key and the parameters set at initialization.
  123. A cipher object is stateful: once you have encrypted a message
  124. you cannot encrypt (or decrypt) another message using the same
  125. object.
  126. The data to encrypt can be broken up in two or
  127. more pieces and `encrypt` can be called multiple times.
  128. That is, the statement:
  129. >>> c.encrypt(a) + c.encrypt(b)
  130. is equivalent to:
  131. >>> c.encrypt(a+b)
  132. This function does not add any padding to the plaintext.
  133. :Parameters:
  134. plaintext : bytes/bytearray/memoryview
  135. The piece of data to encrypt.
  136. It can be of any length.
  137. :Keywords:
  138. output : bytearray/memoryview
  139. The location where the ciphertext must be written to.
  140. If ``None``, the ciphertext is returned.
  141. :Return:
  142. If ``output`` is ``None``, the ciphertext is returned as ``bytes``.
  143. Otherwise, ``None``.
  144. """
  145. if self.encrypt not in self._next:
  146. raise TypeError("encrypt() cannot be called after decrypt()")
  147. self._next = [self.encrypt]
  148. if output is None:
  149. ciphertext = create_string_buffer(len(plaintext))
  150. else:
  151. ciphertext = output
  152. if not is_writeable_buffer(output):
  153. raise TypeError("output must be a bytearray or a writeable memoryview")
  154. if len(plaintext) != len(output):
  155. raise ValueError("output must have the same length as the input"
  156. " (%d bytes)" % len(plaintext))
  157. result = raw_ctr_lib.CTR_encrypt(self._state.get(),
  158. c_uint8_ptr(plaintext),
  159. c_uint8_ptr(ciphertext),
  160. c_size_t(len(plaintext)))
  161. if result:
  162. if result == 0x60002:
  163. raise OverflowError("The counter has wrapped around in"
  164. " CTR mode")
  165. raise ValueError("Error %X while encrypting in CTR mode" % result)
  166. if output is None:
  167. return get_raw_buffer(ciphertext)
  168. else:
  169. return None
  170. def decrypt(self, ciphertext, output=None):
  171. """Decrypt data with the key and the parameters set at initialization.
  172. A cipher object is stateful: once you have decrypted a message
  173. you cannot decrypt (or encrypt) another message with the same
  174. object.
  175. The data to decrypt can be broken up in two or
  176. more pieces and `decrypt` can be called multiple times.
  177. That is, the statement:
  178. >>> c.decrypt(a) + c.decrypt(b)
  179. is equivalent to:
  180. >>> c.decrypt(a+b)
  181. This function does not remove any padding from the plaintext.
  182. :Parameters:
  183. ciphertext : bytes/bytearray/memoryview
  184. The piece of data to decrypt.
  185. It can be of any length.
  186. :Keywords:
  187. output : bytearray/memoryview
  188. The location where the plaintext must be written to.
  189. If ``None``, the plaintext is returned.
  190. :Return:
  191. If ``output`` is ``None``, the plaintext is returned as ``bytes``.
  192. Otherwise, ``None``.
  193. """
  194. if self.decrypt not in self._next:
  195. raise TypeError("decrypt() cannot be called after encrypt()")
  196. self._next = [self.decrypt]
  197. if output is None:
  198. plaintext = create_string_buffer(len(ciphertext))
  199. else:
  200. plaintext = output
  201. if not is_writeable_buffer(output):
  202. raise TypeError("output must be a bytearray or a writeable memoryview")
  203. if len(ciphertext) != len(output):
  204. raise ValueError("output must have the same length as the input"
  205. " (%d bytes)" % len(plaintext))
  206. result = raw_ctr_lib.CTR_decrypt(self._state.get(),
  207. c_uint8_ptr(ciphertext),
  208. c_uint8_ptr(plaintext),
  209. c_size_t(len(ciphertext)))
  210. if result:
  211. if result == 0x60002:
  212. raise OverflowError("The counter has wrapped around in"
  213. " CTR mode")
  214. raise ValueError("Error %X while decrypting in CTR mode" % result)
  215. if output is None:
  216. return get_raw_buffer(plaintext)
  217. else:
  218. return None
  219. def _create_ctr_cipher(factory, **kwargs):
  220. """Instantiate a cipher object that performs CTR encryption/decryption.
  221. :Parameters:
  222. factory : module
  223. The underlying block cipher, a module from ``Crypto.Cipher``.
  224. :Keywords:
  225. nonce : bytes/bytearray/memoryview
  226. The fixed part at the beginning of the counter block - the rest is
  227. the counter number that gets increased when processing the next block.
  228. The nonce must be such that no two messages are encrypted under the
  229. same key and the same nonce.
  230. The nonce must be shorter than the block size (it can have
  231. zero length; the counter is then as long as the block).
  232. If this parameter is not present, a random nonce will be created with
  233. length equal to half the block size. No random nonce shorter than
  234. 64 bits will be created though - you must really think through all
  235. security consequences of using such a short block size.
  236. initial_value : posive integer or bytes/bytearray/memoryview
  237. The initial value for the counter. If not present, the cipher will
  238. start counting from 0. The value is incremented by one for each block.
  239. The counter number is encoded in big endian mode.
  240. counter : object
  241. Instance of ``Crypto.Util.Counter``, which allows full customization
  242. of the counter block. This parameter is incompatible to both ``nonce``
  243. and ``initial_value``.
  244. Any other keyword will be passed to the underlying block cipher.
  245. See the relevant documentation for details (at least ``key`` will need
  246. to be present).
  247. """
  248. cipher_state = factory._create_base_cipher(kwargs)
  249. counter = kwargs.pop("counter", None)
  250. nonce = kwargs.pop("nonce", None)
  251. initial_value = kwargs.pop("initial_value", None)
  252. if kwargs:
  253. raise TypeError("Invalid parameters for CTR mode: %s" % str(kwargs))
  254. if counter is not None and (nonce, initial_value) != (None, None):
  255. raise TypeError("'counter' and 'nonce'/'initial_value'"
  256. " are mutually exclusive")
  257. if counter is None:
  258. # Crypto.Util.Counter is not used
  259. if nonce is None:
  260. if factory.block_size < 16:
  261. raise TypeError("Impossible to create a safe nonce for short"
  262. " block sizes")
  263. nonce = get_random_bytes(factory.block_size // 2)
  264. else:
  265. if len(nonce) >= factory.block_size:
  266. raise ValueError("Nonce is too long")
  267. # What is not nonce is counter
  268. counter_len = factory.block_size - len(nonce)
  269. if initial_value is None:
  270. initial_value = 0
  271. if is_native_int(initial_value):
  272. if (1 << (counter_len * 8)) - 1 < initial_value:
  273. raise ValueError("Initial counter value is too large")
  274. initial_counter_block = nonce + long_to_bytes(initial_value, counter_len)
  275. else:
  276. if len(initial_value) != counter_len:
  277. raise ValueError("Incorrect length for counter byte string (%d bytes, expected %d)" % (len(initial_value), counter_len))
  278. initial_counter_block = nonce + initial_value
  279. return CtrMode(cipher_state,
  280. initial_counter_block,
  281. len(nonce), # prefix
  282. counter_len,
  283. False) # little_endian
  284. # Crypto.Util.Counter is used
  285. # 'counter' used to be a callable object, but now it is
  286. # just a dictionary for backward compatibility.
  287. _counter = dict(counter)
  288. try:
  289. counter_len = _counter.pop("counter_len")
  290. prefix = _counter.pop("prefix")
  291. suffix = _counter.pop("suffix")
  292. initial_value = _counter.pop("initial_value")
  293. little_endian = _counter.pop("little_endian")
  294. except KeyError:
  295. raise TypeError("Incorrect counter object"
  296. " (use Crypto.Util.Counter.new)")
  297. # Compute initial counter block
  298. words = []
  299. while initial_value > 0:
  300. words.append(struct.pack('B', initial_value & 255))
  301. initial_value >>= 8
  302. words += [ b'\x00' ] * max(0, counter_len - len(words))
  303. if not little_endian:
  304. words.reverse()
  305. initial_counter_block = prefix + b"".join(words) + suffix
  306. if len(initial_counter_block) != factory.block_size:
  307. raise ValueError("Size of the counter block (%d bytes) must match"
  308. " block size (%d)" % (len(initial_counter_block),
  309. factory.block_size))
  310. return CtrMode(cipher_state, initial_counter_block,
  311. len(prefix), counter_len, little_endian)