_mode_cfb.py 8.8 KB

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