_mode_cbc.py 8.7 KB

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