_mode_cbc.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. # ===================================================================
  2. #
  3. # Copyright (c) 2014, Legrandin <helderijs@gmail.com>
  4. # All rights reserved.
  5. #
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions
  8. # are met:
  9. #
  10. # 1. Redistributions of source code must retain the above copyright
  11. # notice, this list of conditions and the following disclaimer.
  12. # 2. Redistributions in binary form must reproduce the above copyright
  13. # notice, this list of conditions and the following disclaimer in
  14. # the documentation and/or other materials provided with the
  15. # distribution.
  16. #
  17. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  18. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  19. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  20. # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  21. # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  22. # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  23. # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  25. # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  26. # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  27. # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  28. # POSSIBILITY OF SUCH DAMAGE.
  29. # ===================================================================
  30. """
  31. Ciphertext Block Chaining (CBC) mode.
  32. """
  33. __all__ = ['CbcMode']
  34. from tls.Crypto.Util.py3compat import _copy_bytes
  35. from tls.Crypto.Util._raw_api import (load_pycryptodome_raw_lib, VoidPointer,
  36. create_string_buffer, get_raw_buffer,
  37. SmartPointer, c_size_t, c_uint8_ptr,
  38. is_writeable_buffer)
  39. from tls.Crypto.Random import get_random_bytes
  40. raw_cbc_lib = load_pycryptodome_raw_lib("Crypto.Cipher._raw_cbc", """
  41. int CBC_start_operation(void *cipher,
  42. const uint8_t iv[],
  43. size_t iv_len,
  44. void **pResult);
  45. int CBC_encrypt(void *cbcState,
  46. const uint8_t *in,
  47. uint8_t *out,
  48. size_t data_len);
  49. int CBC_decrypt(void *cbcState,
  50. const uint8_t *in,
  51. uint8_t *out,
  52. size_t data_len);
  53. int CBC_stop_operation(void *state);
  54. """
  55. )
  56. class CbcMode(object):
  57. """*Cipher-Block Chaining (CBC)*.
  58. Each of the ciphertext blocks depends on the current
  59. and all previous plaintext blocks.
  60. An Initialization Vector (*IV*) is required.
  61. See `NIST SP800-38A`_ , Section 6.2 .
  62. .. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf
  63. :undocumented: __init__
  64. """
  65. def __init__(self, block_cipher, iv):
  66. """Create a new block cipher, configured in CBC mode.
  67. :Parameters:
  68. block_cipher : C pointer
  69. A smart pointer to the low-level block cipher instance.
  70. iv : bytes/bytearray/memoryview
  71. The initialization vector to use for encryption or decryption.
  72. It is as long as the cipher block.
  73. **The IV must be unpredictable**. Ideally it is picked randomly.
  74. Reusing the *IV* for encryptions performed with the same key
  75. compromises confidentiality.
  76. """
  77. self._state = VoidPointer()
  78. result = raw_cbc_lib.CBC_start_operation(block_cipher.get(),
  79. c_uint8_ptr(iv),
  80. c_size_t(len(iv)),
  81. self._state.address_of())
  82. if result:
  83. raise ValueError("Error %d while instantiating the CBC mode"
  84. % result)
  85. # Ensure that object disposal of this Python object will (eventually)
  86. # free the memory allocated by the raw library for the cipher mode
  87. self._state = SmartPointer(self._state.get(),
  88. raw_cbc_lib.CBC_stop_operation)
  89. # Memory allocated for the underlying block cipher is now owed
  90. # by the cipher mode
  91. block_cipher.release()
  92. self.block_size = len(iv)
  93. """The block size of the underlying cipher, in bytes."""
  94. self.iv = _copy_bytes(None, None, iv)
  95. """The Initialization Vector originally used to create the object.
  96. The value does not change."""
  97. self.IV = self.iv
  98. """Alias for `iv`"""
  99. self._next = [ self.encrypt, self.decrypt ]
  100. def encrypt(self, plaintext, output=None):
  101. """Encrypt data with the key and the parameters set at initialization.
  102. A cipher object is stateful: once you have encrypted a message
  103. you cannot encrypt (or decrypt) another message using the same
  104. object.
  105. The data to encrypt can be broken up in two or
  106. more pieces and `encrypt` can be called multiple times.
  107. That is, the statement:
  108. >>> c.encrypt(a) + c.encrypt(b)
  109. is equivalent to:
  110. >>> c.encrypt(a+b)
  111. That also means that you cannot reuse an object for encrypting
  112. or decrypting other data with the same key.
  113. This function does not add any padding to the plaintext.
  114. :Parameters:
  115. plaintext : bytes/bytearray/memoryview
  116. The piece of data to encrypt.
  117. Its lenght must be multiple of the cipher block size.
  118. :Keywords:
  119. output : bytearray/memoryview
  120. The location where the ciphertext must be written to.
  121. If ``None``, the ciphertext is returned.
  122. :Return:
  123. If ``output`` is ``None``, the ciphertext is returned as ``bytes``.
  124. Otherwise, ``None``.
  125. """
  126. if self.encrypt not in self._next:
  127. raise TypeError("encrypt() cannot be called after decrypt()")
  128. self._next = [ self.encrypt ]
  129. if output is None:
  130. ciphertext = create_string_buffer(len(plaintext))
  131. else:
  132. ciphertext = output
  133. if not is_writeable_buffer(output):
  134. raise TypeError("output must be a bytearray or a writeable memoryview")
  135. if len(plaintext) != len(output):
  136. raise ValueError("output must have the same length as the input"
  137. " (%d bytes)" % len(plaintext))
  138. result = raw_cbc_lib.CBC_encrypt(self._state.get(),
  139. c_uint8_ptr(plaintext),
  140. c_uint8_ptr(ciphertext),
  141. c_size_t(len(plaintext)))
  142. if result:
  143. if result == 3:
  144. raise ValueError("Data must be padded to %d byte boundary in CBC mode" % self.block_size)
  145. raise ValueError("Error %d while encrypting in CBC mode" % result)
  146. if output is None:
  147. return get_raw_buffer(ciphertext)
  148. else:
  149. return None
  150. def decrypt(self, ciphertext, output=None):
  151. """Decrypt data with the key and the parameters set at initialization.
  152. A cipher object is stateful: once you have decrypted a message
  153. you cannot decrypt (or encrypt) another message with the same
  154. object.
  155. The data to decrypt can be broken up in two or
  156. more pieces and `decrypt` can be called multiple times.
  157. That is, the statement:
  158. >>> c.decrypt(a) + c.decrypt(b)
  159. is equivalent to:
  160. >>> c.decrypt(a+b)
  161. This function does not remove any padding from the plaintext.
  162. :Parameters:
  163. ciphertext : bytes/bytearray/memoryview
  164. The piece of data to decrypt.
  165. Its length must be multiple of the cipher block size.
  166. :Keywords:
  167. output : bytearray/memoryview
  168. The location where the plaintext must be written to.
  169. If ``None``, the plaintext is returned.
  170. :Return:
  171. If ``output`` is ``None``, the plaintext is returned as ``bytes``.
  172. Otherwise, ``None``.
  173. """
  174. if self.decrypt not in self._next:
  175. raise TypeError("decrypt() cannot be called after encrypt()")
  176. self._next = [ self.decrypt ]
  177. if output is None:
  178. plaintext = create_string_buffer(len(ciphertext))
  179. else:
  180. plaintext = output
  181. if not is_writeable_buffer(output):
  182. raise TypeError("output must be a bytearray or a writeable memoryview")
  183. if len(ciphertext) != len(output):
  184. raise ValueError("output must have the same length as the input"
  185. " (%d bytes)" % len(plaintext))
  186. result = raw_cbc_lib.CBC_decrypt(self._state.get(),
  187. c_uint8_ptr(ciphertext),
  188. c_uint8_ptr(plaintext),
  189. c_size_t(len(ciphertext)))
  190. if result:
  191. if result == 3:
  192. raise ValueError("Data must be padded to %d byte boundary in CBC mode" % self.block_size)
  193. raise ValueError("Error %d while decrypting in CBC mode" % result)
  194. if output is None:
  195. return get_raw_buffer(plaintext)
  196. else:
  197. return None
  198. def _create_cbc_cipher(factory, **kwargs):
  199. """Instantiate a cipher object that performs CBC encryption/decryption.
  200. :Parameters:
  201. factory : module
  202. The underlying block cipher, a module from ``Crypto.Cipher``.
  203. :Keywords:
  204. iv : bytes/bytearray/memoryview
  205. The IV to use for CBC.
  206. IV : bytes/bytearray/memoryview
  207. Alias for ``iv``.
  208. Any other keyword will be passed to the underlying block cipher.
  209. See the relevant documentation for details (at least ``key`` will need
  210. to be present).
  211. """
  212. cipher_state = factory._create_base_cipher(kwargs)
  213. iv = kwargs.pop("IV", None)
  214. IV = kwargs.pop("iv", None)
  215. if (None, None) == (iv, IV):
  216. iv = get_random_bytes(factory.block_size)
  217. if iv is not None:
  218. if IV is not None:
  219. raise TypeError("You must either use 'iv' or 'IV', not both")
  220. else:
  221. iv = IV
  222. if len(iv) != factory.block_size:
  223. raise ValueError("Incorrect IV length (it must be %d bytes long)" %
  224. factory.block_size)
  225. if kwargs:
  226. raise TypeError("Unknown parameters for CBC: %s" % str(kwargs))
  227. return CbcMode(cipher_state, iv)