_mode_ecb.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Cipher/mode_ecb.py : ECB 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. Electronic Code Book (ECB) mode.
  24. """
  25. __all__ = [ 'EcbMode' ]
  26. from tls.Crypto.Util._raw_api import (load_pycryptodome_raw_lib,
  27. VoidPointer, create_string_buffer,
  28. get_raw_buffer, SmartPointer,
  29. c_size_t, c_uint8_ptr,
  30. is_writeable_buffer)
  31. raw_ecb_lib = load_pycryptodome_raw_lib("Crypto.Cipher._raw_ecb", """
  32. int ECB_start_operation(void *cipher,
  33. void **pResult);
  34. int ECB_encrypt(void *ecbState,
  35. const uint8_t *in,
  36. uint8_t *out,
  37. size_t data_len);
  38. int ECB_decrypt(void *ecbState,
  39. const uint8_t *in,
  40. uint8_t *out,
  41. size_t data_len);
  42. int ECB_stop_operation(void *state);
  43. """
  44. )
  45. class EcbMode(object):
  46. """*Electronic Code Book (ECB)*.
  47. This is the simplest encryption mode. Each of the plaintext blocks
  48. is directly encrypted into a ciphertext block, independently of
  49. any other block.
  50. This mode is dangerous because it exposes frequency of symbols
  51. in your plaintext. Other modes (e.g. *CBC*) should be used instead.
  52. See `NIST SP800-38A`_ , Section 6.1.
  53. .. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf
  54. :undocumented: __init__
  55. """
  56. def __init__(self, block_cipher):
  57. """Create a new block cipher, configured in ECB mode.
  58. :Parameters:
  59. block_cipher : C pointer
  60. A smart pointer to the low-level block cipher instance.
  61. """
  62. self._state = VoidPointer()
  63. result = raw_ecb_lib.ECB_start_operation(block_cipher.get(),
  64. self._state.address_of())
  65. if result:
  66. raise ValueError("Error %d while instantiating the ECB mode"
  67. % result)
  68. # Ensure that object disposal of this Python object will (eventually)
  69. # free the memory allocated by the raw library for the cipher
  70. # mode
  71. self._state = SmartPointer(self._state.get(),
  72. raw_ecb_lib.ECB_stop_operation)
  73. # Memory allocated for the underlying block cipher is now owned
  74. # by the cipher mode
  75. block_cipher.release()
  76. def encrypt(self, plaintext, output=None):
  77. """Encrypt data with the key set at initialization.
  78. The data to encrypt can be broken up in two or
  79. more pieces and `encrypt` can be called multiple times.
  80. That is, the statement:
  81. >>> c.encrypt(a) + c.encrypt(b)
  82. is equivalent to:
  83. >>> c.encrypt(a+b)
  84. This function does not add any padding to the plaintext.
  85. :Parameters:
  86. plaintext : bytes/bytearray/memoryview
  87. The piece of data to encrypt.
  88. The length must be multiple of the cipher block length.
  89. :Keywords:
  90. output : bytearray/memoryview
  91. The location where the ciphertext must be written to.
  92. If ``None``, the ciphertext is returned.
  93. :Return:
  94. If ``output`` is ``None``, the ciphertext is returned as ``bytes``.
  95. Otherwise, ``None``.
  96. """
  97. if output is None:
  98. ciphertext = create_string_buffer(len(plaintext))
  99. else:
  100. ciphertext = output
  101. if not is_writeable_buffer(output):
  102. raise TypeError("output must be a bytearray or a writeable memoryview")
  103. if len(plaintext) != len(output):
  104. raise ValueError("output must have the same length as the input"
  105. " (%d bytes)" % len(plaintext))
  106. result = raw_ecb_lib.ECB_encrypt(self._state.get(),
  107. c_uint8_ptr(plaintext),
  108. c_uint8_ptr(ciphertext),
  109. c_size_t(len(plaintext)))
  110. if result:
  111. if result == 3:
  112. raise ValueError("Data must be aligned to block boundary in ECB mode")
  113. raise ValueError("Error %d while encrypting in ECB mode" % result)
  114. if output is None:
  115. return get_raw_buffer(ciphertext)
  116. else:
  117. return None
  118. def decrypt(self, ciphertext, output=None):
  119. """Decrypt data with the key set at initialization.
  120. The data to decrypt can be broken up in two or
  121. more pieces and `decrypt` can be called multiple times.
  122. That is, the statement:
  123. >>> c.decrypt(a) + c.decrypt(b)
  124. is equivalent to:
  125. >>> c.decrypt(a+b)
  126. This function does not remove any padding from the plaintext.
  127. :Parameters:
  128. ciphertext : bytes/bytearray/memoryview
  129. The piece of data to decrypt.
  130. The length must be multiple of the cipher block length.
  131. :Keywords:
  132. output : bytearray/memoryview
  133. The location where the plaintext must be written to.
  134. If ``None``, the plaintext is returned.
  135. :Return:
  136. If ``output`` is ``None``, the plaintext is returned as ``bytes``.
  137. Otherwise, ``None``.
  138. """
  139. if output is None:
  140. plaintext = create_string_buffer(len(ciphertext))
  141. else:
  142. plaintext = output
  143. if not is_writeable_buffer(output):
  144. raise TypeError("output must be a bytearray or a writeable memoryview")
  145. if len(ciphertext) != len(output):
  146. raise ValueError("output must have the same length as the input"
  147. " (%d bytes)" % len(plaintext))
  148. result = raw_ecb_lib.ECB_decrypt(self._state.get(),
  149. c_uint8_ptr(ciphertext),
  150. c_uint8_ptr(plaintext),
  151. c_size_t(len(ciphertext)))
  152. if result:
  153. if result == 3:
  154. raise ValueError("Data must be aligned to block boundary in ECB mode")
  155. raise ValueError("Error %d while decrypting in ECB mode" % result)
  156. if output is None:
  157. return get_raw_buffer(plaintext)
  158. else:
  159. return None
  160. def _create_ecb_cipher(factory, **kwargs):
  161. """Instantiate a cipher object that performs ECB encryption/decryption.
  162. :Parameters:
  163. factory : module
  164. The underlying block cipher, a module from ``Crypto.Cipher``.
  165. All keywords are passed to the underlying block cipher.
  166. See the relevant documentation for details (at least ``key`` will need
  167. to be present"""
  168. cipher_state = factory._create_base_cipher(kwargs)
  169. if kwargs:
  170. raise TypeError("Unknown parameters for ECB: %s" % str(kwargs))
  171. return EcbMode(cipher_state)