_mode_ofb.py 8.3 KB

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