_mode_cfb.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Cipher/mode_cfb.py : CFB 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 Feedback (CFB) mode.
  24. """
  25. __all__ = ['CfbMode']
  26. from tls.Crypto.Util.py3compat import _copy_bytes
  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. raw_cfb_lib = load_pycryptodome_raw_lib("Crypto.Cipher._raw_cfb","""
  33. int CFB_start_operation(void *cipher,
  34. const uint8_t iv[],
  35. size_t iv_len,
  36. size_t segment_len, /* In bytes */
  37. void **pResult);
  38. int CFB_encrypt(void *cfbState,
  39. const uint8_t *in,
  40. uint8_t *out,
  41. size_t data_len);
  42. int CFB_decrypt(void *cfbState,
  43. const uint8_t *in,
  44. uint8_t *out,
  45. size_t data_len);
  46. int CFB_stop_operation(void *state);"""
  47. )
  48. class CfbMode(object):
  49. """*Cipher FeedBack (CFB)*.
  50. This mode is similar to CFB, but it transforms
  51. the underlying block cipher into a stream cipher.
  52. Plaintext and ciphertext are processed in *segments*
  53. of **s** bits. The mode is therefore sometimes
  54. labelled **s**-bit CFB.
  55. An Initialization Vector (*IV*) is required.
  56. See `NIST SP800-38A`_ , Section 6.3.
  57. .. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf
  58. :undocumented: __init__
  59. """
  60. def __init__(self, block_cipher, iv, segment_size):
  61. """Create a new block cipher, configured in CFB mode.
  62. :Parameters:
  63. block_cipher : C pointer
  64. A smart pointer to the low-level block cipher instance.
  65. iv : bytes/bytearray/memoryview
  66. The initialization vector to use for encryption or decryption.
  67. It is as long as the cipher block.
  68. **The IV must be unpredictable**. Ideally it is picked randomly.
  69. Reusing the *IV* for encryptions performed with the same key
  70. compromises confidentiality.
  71. segment_size : integer
  72. The number of bytes the plaintext and ciphertext are segmented in.
  73. """
  74. self._state = VoidPointer()
  75. result = raw_cfb_lib.CFB_start_operation(block_cipher.get(),
  76. c_uint8_ptr(iv),
  77. c_size_t(len(iv)),
  78. c_size_t(segment_size),
  79. self._state.address_of())
  80. if result:
  81. raise ValueError("Error %d while instantiating the CFB mode" % result)
  82. # Ensure that object disposal of this Python object will (eventually)
  83. # free the memory allocated by the raw library for the cipher mode
  84. self._state = SmartPointer(self._state.get(),
  85. raw_cfb_lib.CFB_stop_operation)
  86. # Memory allocated for the underlying block cipher is now owed
  87. # by the cipher mode
  88. block_cipher.release()
  89. self.block_size = len(iv)
  90. """The block size of the underlying cipher, in bytes."""
  91. self.iv = _copy_bytes(None, None, iv)
  92. """The Initialization Vector originally used to create the object.
  93. The value does not change."""
  94. self.IV = self.iv
  95. """Alias for `iv`"""
  96. self._next = [ self.encrypt, self.decrypt ]
  97. def encrypt(self, plaintext, output=None):
  98. """Encrypt data with the key and the parameters set at initialization.
  99. A cipher object is stateful: once you have encrypted a message
  100. you cannot encrypt (or decrypt) another message using the same
  101. object.
  102. The data to encrypt can be broken up in two or
  103. more pieces and `encrypt` can be called multiple times.
  104. That is, the statement:
  105. >>> c.encrypt(a) + c.encrypt(b)
  106. is equivalent to:
  107. >>> c.encrypt(a+b)
  108. This function does not add any padding to the plaintext.
  109. :Parameters:
  110. plaintext : bytes/bytearray/memoryview
  111. The piece of data to encrypt.
  112. It can be of any length.
  113. :Keywords:
  114. output : bytearray/memoryview
  115. The location where the ciphertext must be written to.
  116. If ``None``, the ciphertext is returned.
  117. :Return:
  118. If ``output`` is ``None``, the ciphertext is returned as ``bytes``.
  119. Otherwise, ``None``.
  120. """
  121. if self.encrypt not in self._next:
  122. raise TypeError("encrypt() cannot be called after decrypt()")
  123. self._next = [ self.encrypt ]
  124. if output is None:
  125. ciphertext = create_string_buffer(len(plaintext))
  126. else:
  127. ciphertext = output
  128. if not is_writeable_buffer(output):
  129. raise TypeError("output must be a bytearray or a writeable memoryview")
  130. if len(plaintext) != len(output):
  131. raise ValueError("output must have the same length as the input"
  132. " (%d bytes)" % len(plaintext))
  133. result = raw_cfb_lib.CFB_encrypt(self._state.get(),
  134. c_uint8_ptr(plaintext),
  135. c_uint8_ptr(ciphertext),
  136. c_size_t(len(plaintext)))
  137. if result:
  138. raise ValueError("Error %d while encrypting in CFB mode" % result)
  139. if output is None:
  140. return get_raw_buffer(ciphertext)
  141. else:
  142. return None
  143. def decrypt(self, ciphertext, output=None):
  144. """Decrypt data with the key and the parameters set at initialization.
  145. A cipher object is stateful: once you have decrypted a message
  146. you cannot decrypt (or encrypt) another message with the same
  147. object.
  148. The data to decrypt can be broken up in two or
  149. more pieces and `decrypt` can be called multiple times.
  150. That is, the statement:
  151. >>> c.decrypt(a) + c.decrypt(b)
  152. is equivalent to:
  153. >>> c.decrypt(a+b)
  154. This function does not remove any padding from the plaintext.
  155. :Parameters:
  156. ciphertext : bytes/bytearray/memoryview
  157. The piece of data to decrypt.
  158. It can be of any length.
  159. :Keywords:
  160. output : bytearray/memoryview
  161. The location where the plaintext must be written to.
  162. If ``None``, the plaintext is returned.
  163. :Return:
  164. If ``output`` is ``None``, the plaintext is returned as ``bytes``.
  165. Otherwise, ``None``.
  166. """
  167. if self.decrypt not in self._next:
  168. raise TypeError("decrypt() cannot be called after encrypt()")
  169. self._next = [ self.decrypt ]
  170. if output is None:
  171. plaintext = create_string_buffer(len(ciphertext))
  172. else:
  173. plaintext = output
  174. if not is_writeable_buffer(output):
  175. raise TypeError("output must be a bytearray or a writeable memoryview")
  176. if len(ciphertext) != len(output):
  177. raise ValueError("output must have the same length as the input"
  178. " (%d bytes)" % len(plaintext))
  179. result = raw_cfb_lib.CFB_decrypt(self._state.get(),
  180. c_uint8_ptr(ciphertext),
  181. c_uint8_ptr(plaintext),
  182. c_size_t(len(ciphertext)))
  183. if result:
  184. raise ValueError("Error %d while decrypting in CFB mode" % result)
  185. if output is None:
  186. return get_raw_buffer(plaintext)
  187. else:
  188. return None
  189. def _create_cfb_cipher(factory, **kwargs):
  190. """Instantiate a cipher object that performs CFB encryption/decryption.
  191. :Parameters:
  192. factory : module
  193. The underlying block cipher, a module from ``Crypto.Cipher``.
  194. :Keywords:
  195. iv : bytes/bytearray/memoryview
  196. The IV to use for CFB.
  197. IV : bytes/bytearray/memoryview
  198. Alias for ``iv``.
  199. segment_size : integer
  200. The number of bit the plaintext and ciphertext are segmented in.
  201. If not present, the default is 8.
  202. Any other keyword will be passed to the underlying block cipher.
  203. See the relevant documentation for details (at least ``key`` will need
  204. to be present).
  205. """
  206. cipher_state = factory._create_base_cipher(kwargs)
  207. iv = kwargs.pop("IV", None)
  208. IV = kwargs.pop("iv", None)
  209. if (None, None) == (iv, IV):
  210. iv = get_random_bytes(factory.block_size)
  211. if iv is not None:
  212. if IV is not None:
  213. raise TypeError("You must either use 'iv' or 'IV', not both")
  214. else:
  215. iv = IV
  216. if len(iv) != factory.block_size:
  217. raise ValueError("Incorrect IV length (it must be %d bytes long)" %
  218. factory.block_size)
  219. segment_size_bytes, rem = divmod(kwargs.pop("segment_size", 8), 8)
  220. if segment_size_bytes == 0 or rem != 0:
  221. raise ValueError("'segment_size' must be positive and multiple of 8 bits")
  222. if kwargs:
  223. raise TypeError("Unknown parameters for CFB: %s" % str(kwargs))
  224. return CfbMode(cipher_state, iv, segment_size_bytes)