_mode_ctr.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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. from Crypto.Util._raw_api import (load_pycryptodome_raw_lib, VoidPointer,
  27. create_string_buffer, get_raw_buffer,
  28. SmartPointer, c_size_t, expect_byte_string)
  29. from Crypto.Random import get_random_bytes
  30. from Crypto.Util.py3compat import b, bchr
  31. from Crypto.Util.number import long_to_bytes
  32. raw_ctr_lib = load_pycryptodome_raw_lib("Crypto.Cipher._raw_ctr", """
  33. int CTR_start_operation(void *cipher,
  34. uint8_t initialCounterBlock[],
  35. size_t initialCounterBlock_len,
  36. size_t prefix_len,
  37. unsigned counter_len,
  38. unsigned littleEndian,
  39. void **pResult);
  40. int CTR_encrypt(void *ctrState,
  41. const uint8_t *in,
  42. uint8_t *out,
  43. size_t data_len);
  44. int CTR_decrypt(void *ctrState,
  45. const uint8_t *in,
  46. uint8_t *out,
  47. size_t data_len);
  48. int CTR_stop_operation(void *ctrState);"""
  49. )
  50. class CtrMode(object):
  51. """*CounTeR (CTR)* mode.
  52. This mode is very similar to ECB, in that
  53. encryption of one block is done independently of all other blocks.
  54. Unlike ECB, the block *position* contributes to the encryption
  55. and no information leaks about symbol frequency.
  56. Each message block is associated to a *counter* which
  57. must be unique across all messages that get encrypted
  58. with the same key (not just within the same message).
  59. The counter is as big as the block size.
  60. Counters can be generated in several ways. The most
  61. straightword one is to choose an *initial counter block*
  62. (which can be made public, similarly to the *IV* for the
  63. other modes) and increment its lowest **m** bits by one
  64. (modulo *2^m*) for each block. In most cases, **m** is
  65. chosen to be half the block size.
  66. See `NIST SP800-38A`_, Section 6.5 (for the mode) and
  67. Appendix B (for how to manage the *initial counter block*).
  68. .. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf
  69. :undocumented: __init__
  70. """
  71. def __init__(self, block_cipher, initial_counter_block,
  72. prefix_len, counter_len, little_endian):
  73. """Create a new block cipher, configured in CTR mode.
  74. :Parameters:
  75. block_cipher : C pointer
  76. A smart pointer to the low-level block cipher instance.
  77. initial_counter_block : byte string
  78. The initial plaintext to use to generate the key stream.
  79. It is as large as the cipher block, and it embeds
  80. the initial value of the counter.
  81. This value must not be reused.
  82. It shall contain a nonce or a random component.
  83. Reusing the *initial counter block* for encryptions
  84. performed with the same key compromises confidentiality.
  85. prefix_len : integer
  86. The amount of bytes at the beginning of the counter block
  87. that never change.
  88. counter_len : integer
  89. The length in bytes of the counter embedded in the counter
  90. block.
  91. little_endian : boolean
  92. True if the counter in the counter block is an integer encoded
  93. in little endian mode. If False, it is big endian.
  94. """
  95. if len(initial_counter_block) == prefix_len + counter_len:
  96. self.nonce = initial_counter_block[:prefix_len]
  97. """Nonce; not available if there is a fixed suffix"""
  98. expect_byte_string(initial_counter_block)
  99. self._state = VoidPointer()
  100. result = raw_ctr_lib.CTR_start_operation(block_cipher.get(),
  101. initial_counter_block,
  102. c_size_t(len(initial_counter_block)),
  103. c_size_t(prefix_len),
  104. counter_len,
  105. little_endian,
  106. self._state.address_of())
  107. if result:
  108. raise ValueError("Error %X while instatiating the CTR mode"
  109. % result)
  110. # Ensure that object disposal of this Python object will (eventually)
  111. # free the memory allocated by the raw library for the cipher mode
  112. self._state = SmartPointer(self._state.get(),
  113. raw_ctr_lib.CTR_stop_operation)
  114. # Memory allocated for the underlying block cipher is now owed
  115. # by the cipher mode
  116. block_cipher.release()
  117. self.block_size = len(initial_counter_block)
  118. """The block size of the underlying cipher, in bytes."""
  119. self._next = [self.encrypt, self.decrypt]
  120. def encrypt(self, plaintext):
  121. """Encrypt data with the key and the parameters set at initialization.
  122. A cipher object is stateful: once you have encrypted a message
  123. you cannot encrypt (or decrypt) another message using the same
  124. object.
  125. The data to encrypt can be broken up in two or
  126. more pieces and `encrypt` can be called multiple times.
  127. That is, the statement:
  128. >>> c.encrypt(a) + c.encrypt(b)
  129. is equivalent to:
  130. >>> c.encrypt(a+b)
  131. This function does not add any padding to the plaintext.
  132. :Parameters:
  133. plaintext : byte string
  134. The piece of data to encrypt.
  135. It can be of any length.
  136. :Return:
  137. the encrypted data, as a byte string.
  138. It is as long as *plaintext*.
  139. """
  140. if self.encrypt not in self._next:
  141. raise TypeError("encrypt() cannot be called after decrypt()")
  142. self._next = [self.encrypt]
  143. expect_byte_string(plaintext)
  144. ciphertext = create_string_buffer(len(plaintext))
  145. result = raw_ctr_lib.CTR_encrypt(self._state.get(),
  146. plaintext,
  147. ciphertext,
  148. c_size_t(len(plaintext)))
  149. if result:
  150. if result == 0x60002:
  151. raise OverflowError("The counter has wrapped around in"
  152. " CTR mode")
  153. raise ValueError("Error %X while encrypting in CTR mode" % result)
  154. return get_raw_buffer(ciphertext)
  155. def decrypt(self, ciphertext):
  156. """Decrypt data with the key and the parameters set at initialization.
  157. A cipher object is stateful: once you have decrypted a message
  158. you cannot decrypt (or encrypt) another message with the same
  159. object.
  160. The data to decrypt can be broken up in two or
  161. more pieces and `decrypt` can be called multiple times.
  162. That is, the statement:
  163. >>> c.decrypt(a) + c.decrypt(b)
  164. is equivalent to:
  165. >>> c.decrypt(a+b)
  166. This function does not remove any padding from the plaintext.
  167. :Parameters:
  168. ciphertext : byte string
  169. The piece of data to decrypt.
  170. It can be of any length.
  171. :Return: the decrypted data (byte string).
  172. """
  173. if self.decrypt not in self._next:
  174. raise TypeError("decrypt() cannot be called after encrypt()")
  175. self._next = [self.decrypt]
  176. expect_byte_string(ciphertext)
  177. plaintext = create_string_buffer(len(ciphertext))
  178. result = raw_ctr_lib.CTR_decrypt(self._state.get(),
  179. ciphertext,
  180. plaintext,
  181. c_size_t(len(ciphertext)))
  182. if result:
  183. if result == 0x60002:
  184. raise OverflowError("The counter has wrapped around in"
  185. " CTR mode")
  186. raise ValueError("Error %X while decrypting in CTR mode" % result)
  187. return get_raw_buffer(plaintext)
  188. def _create_ctr_cipher(factory, **kwargs):
  189. """Instantiate a cipher object that performs CTR encryption/decryption.
  190. :Parameters:
  191. factory : module
  192. The underlying block cipher, a module from ``Crypto.Cipher``.
  193. :Keywords:
  194. nonce : binary string
  195. The fixed part at the beginning of the counter block - the rest is
  196. the counter number that gets increased when processing the next block.
  197. The nonce must be such that no two messages are encrypted under the
  198. same key and the same nonce.
  199. The nonce must be shorter than the block size (it can have
  200. zero length).
  201. If this parameter is not present, a random nonce will be created with
  202. length equal to half the block size. No random nonce shorter than
  203. 64 bits will be created though - you must really think through all
  204. security consequences of using such a short block size.
  205. initial_value : posive integer
  206. The initial value for the counter. If not present, the cipher will
  207. start counting from 0. The value is incremented by one for each block.
  208. The counter number is encoded in big endian mode.
  209. counter : object
  210. Instance of ``Crypto.Util.Counter``, which allows full customization
  211. of the counter block. This parameter is incompatible to both ``nonce``
  212. and ``initial_value``.
  213. Any other keyword will be passed to the underlying block cipher.
  214. See the relevant documentation for details (at least ``key`` will need
  215. to be present).
  216. """
  217. cipher_state = factory._create_base_cipher(kwargs)
  218. counter = kwargs.pop("counter", None)
  219. nonce = kwargs.pop("nonce", None)
  220. initial_value = kwargs.pop("initial_value", None)
  221. if kwargs:
  222. raise TypeError("Invalid parameters for CTR mode: %s" % str(kwargs))
  223. if counter is not None and (nonce, initial_value) != (None, None):
  224. raise TypeError("'counter' and 'nonce'/'initial_value'"
  225. " are mutually exclusive")
  226. if counter is None:
  227. # Crypto.Util.Counter is not used
  228. if nonce is None:
  229. if factory.block_size < 16:
  230. raise TypeError("Impossible to create a safe nonce for short"
  231. " block sizes")
  232. nonce = get_random_bytes(factory.block_size // 2)
  233. if initial_value is None:
  234. initial_value = 0
  235. if len(nonce) >= factory.block_size:
  236. raise ValueError("Nonce is too long")
  237. counter_len = factory.block_size - len(nonce)
  238. if (1 << (counter_len * 8)) - 1 < initial_value:
  239. raise ValueError("Initial counter value is too large")
  240. return CtrMode(cipher_state,
  241. # initial_counter_block
  242. nonce + long_to_bytes(initial_value, counter_len),
  243. len(nonce), # prefix
  244. counter_len,
  245. False) # little_endian
  246. # Crypto.Util.Counter is used
  247. # 'counter' used to be a callable object, but now it is
  248. # just a dictionary for backward compatibility.
  249. _counter = dict(counter)
  250. try:
  251. counter_len = _counter.pop("counter_len")
  252. prefix = _counter.pop("prefix")
  253. suffix = _counter.pop("suffix")
  254. initial_value = _counter.pop("initial_value")
  255. little_endian = _counter.pop("little_endian")
  256. except KeyError:
  257. raise TypeError("Incorrect counter object"
  258. " (use Crypto.Util.Counter.new)")
  259. # Compute initial counter block
  260. words = []
  261. while initial_value > 0:
  262. words.append(bchr(initial_value & 255))
  263. initial_value >>= 8
  264. words += [bchr(0)] * max(0, counter_len - len(words))
  265. if not little_endian:
  266. words.reverse()
  267. initial_counter_block = prefix + b("").join(words) + suffix
  268. if len(initial_counter_block) != factory.block_size:
  269. raise ValueError("Size of the counter block (% bytes) must match"
  270. " block size (%d)" % (len(initial_counter_block),
  271. factory.block_size))
  272. return CtrMode(cipher_state, initial_counter_block,
  273. len(prefix), counter_len, little_endian)