AES.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Cipher/AES.py : AES
  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. Module's constants for the modes of operation supported with AES:
  24. :var MODE_ECB: :ref:`Electronic Code Book (ECB) <ecb_mode>`
  25. :var MODE_CBC: :ref:`Cipher-Block Chaining (CBC) <cbc_mode>`
  26. :var MODE_CFB: :ref:`Cipher FeedBack (CFB) <cfb_mode>`
  27. :var MODE_OFB: :ref:`Output FeedBack (OFB) <ofb_mode>`
  28. :var MODE_CTR: :ref:`CounTer Mode (CTR) <ctr_mode>`
  29. :var MODE_OPENPGP: :ref:`OpenPGP Mode <openpgp_mode>`
  30. :var MODE_CCM: :ref:`Counter with CBC-MAC (CCM) Mode <ccm_mode>`
  31. :var MODE_EAX: :ref:`EAX Mode <eax_mode>`
  32. :var MODE_GCM: :ref:`Galois Counter Mode (GCM) <gcm_mode>`
  33. :var MODE_SIV: :ref:`Syntethic Initialization Vector (SIV) <siv_mode>`
  34. :var MODE_OCB: :ref:`Offset Code Book (OCB) <ocb_mode>`
  35. """
  36. import sys
  37. from tls.Crypto.Cipher import _create_cipher
  38. from tls.Crypto.Util._raw_api import (load_pycryptodome_raw_lib,
  39. VoidPointer, SmartPointer,
  40. c_size_t, c_uint8_ptr)
  41. from tls.Crypto.Util import _cpu_features
  42. from tls.Crypto.Random import get_random_bytes
  43. _cproto = """
  44. int AES_start_operation(const uint8_t key[],
  45. size_t key_len,
  46. void **pResult);
  47. int AES_encrypt(const void *state,
  48. const uint8_t *in,
  49. uint8_t *out,
  50. size_t data_len);
  51. int AES_decrypt(const void *state,
  52. const uint8_t *in,
  53. uint8_t *out,
  54. size_t data_len);
  55. int AES_stop_operation(void *state);
  56. """
  57. # Load portable AES
  58. _raw_aes_lib = load_pycryptodome_raw_lib("Crypto.Cipher._raw_aes",
  59. _cproto)
  60. # Try to load AES with AES NI instructions
  61. try:
  62. _raw_aesni_lib = None
  63. if _cpu_features.have_aes_ni():
  64. _raw_aesni_lib = load_pycryptodome_raw_lib("Crypto.Cipher._raw_aesni",
  65. _cproto.replace("AES",
  66. "AESNI"))
  67. # _raw_aesni may not have been compiled in
  68. except OSError:
  69. pass
  70. def _create_base_cipher(dict_parameters):
  71. """This method instantiates and returns a handle to a low-level
  72. base cipher. It will absorb named parameters in the process."""
  73. use_aesni = dict_parameters.pop("use_aesni", True)
  74. try:
  75. key = dict_parameters.pop("key")
  76. except KeyError:
  77. raise TypeError("Missing 'key' parameter")
  78. if len(key) not in key_size:
  79. raise ValueError("Incorrect AES key length (%d bytes)" % len(key))
  80. if use_aesni and _raw_aesni_lib:
  81. start_operation = _raw_aesni_lib.AESNI_start_operation
  82. stop_operation = _raw_aesni_lib.AESNI_stop_operation
  83. else:
  84. start_operation = _raw_aes_lib.AES_start_operation
  85. stop_operation = _raw_aes_lib.AES_stop_operation
  86. cipher = VoidPointer()
  87. result = start_operation(c_uint8_ptr(key),
  88. c_size_t(len(key)),
  89. cipher.address_of())
  90. if result:
  91. raise ValueError("Error %X while instantiating the AES cipher"
  92. % result)
  93. return SmartPointer(cipher.get(), stop_operation)
  94. def _derive_Poly1305_key_pair(key, nonce):
  95. """Derive a tuple (r, s, nonce) for a Poly1305 MAC.
  96. If nonce is ``None``, a new 16-byte nonce is generated.
  97. """
  98. if len(key) != 32:
  99. raise ValueError("Poly1305 with AES requires a 32-byte key")
  100. if nonce is None:
  101. nonce = get_random_bytes(16)
  102. elif len(nonce) != 16:
  103. raise ValueError("Poly1305 with AES requires a 16-byte nonce")
  104. s = new(key[:16], MODE_ECB).encrypt(nonce)
  105. return key[16:], s, nonce
  106. def new(key, mode, *args, **kwargs):
  107. """Create a new AES cipher.
  108. :param key:
  109. The secret key to use in the symmetric cipher.
  110. It must be 16, 24 or 32 bytes long (respectively for *AES-128*,
  111. *AES-192* or *AES-256*).
  112. For ``MODE_SIV`` only, it doubles to 32, 48, or 64 bytes.
  113. :type key: bytes/bytearray/memoryview
  114. :param mode:
  115. The chaining mode to use for encryption or decryption.
  116. If in doubt, use ``MODE_EAX``.
  117. :type mode: One of the supported ``MODE_*`` constants
  118. :Keyword Arguments:
  119. * **iv** (*bytes*, *bytearray*, *memoryview*) --
  120. (Only applicable for ``MODE_CBC``, ``MODE_CFB``, ``MODE_OFB``,
  121. and ``MODE_OPENPGP`` modes).
  122. The initialization vector to use for encryption or decryption.
  123. For ``MODE_CBC``, ``MODE_CFB``, and ``MODE_OFB`` it must be 16 bytes long.
  124. For ``MODE_OPENPGP`` mode only,
  125. it must be 16 bytes long for encryption
  126. and 18 bytes for decryption (in the latter case, it is
  127. actually the *encrypted* IV which was prefixed to the ciphertext).
  128. If not provided, a random byte string is generated (you must then
  129. read its value with the :attr:`iv` attribute).
  130. * **nonce** (*bytes*, *bytearray*, *memoryview*) --
  131. (Only applicable for ``MODE_CCM``, ``MODE_EAX``, ``MODE_GCM``,
  132. ``MODE_SIV``, ``MODE_OCB``, and ``MODE_CTR``).
  133. A value that must never be reused for any other encryption done
  134. with this key (except possibly for ``MODE_SIV``, see below).
  135. For ``MODE_EAX``, ``MODE_GCM`` and ``MODE_SIV`` there are no
  136. restrictions on its length (recommended: **16** bytes).
  137. For ``MODE_CCM``, its length must be in the range **[7..13]**.
  138. Bear in mind that with CCM there is a trade-off between nonce
  139. length and maximum message size. Recommendation: **11** bytes.
  140. For ``MODE_OCB``, its length must be in the range **[1..15]**
  141. (recommended: **15**).
  142. For ``MODE_CTR``, its length must be in the range **[0..15]**
  143. (recommended: **8**).
  144. For ``MODE_SIV``, the nonce is optional, if it is not specified,
  145. then no nonce is being used, which renders the encryption
  146. deterministic.
  147. If not provided, for modes other than ``MODE_SIV```, a random
  148. byte string of the recommended length is used (you must then
  149. read its value with the :attr:`nonce` attribute).
  150. * **segment_size** (*integer*) --
  151. (Only ``MODE_CFB``).The number of **bits** the plaintext and ciphertext
  152. are segmented in. It must be a multiple of 8.
  153. If not specified, it will be assumed to be 8.
  154. * **mac_len** : (*integer*) --
  155. (Only ``MODE_EAX``, ``MODE_GCM``, ``MODE_OCB``, ``MODE_CCM``)
  156. Length of the authentication tag, in bytes.
  157. It must be even and in the range **[4..16]**.
  158. The recommended value (and the default, if not specified) is **16**.
  159. * **msg_len** : (*integer*) --
  160. (Only ``MODE_CCM``). Length of the message to (de)cipher.
  161. If not specified, ``encrypt`` must be called with the entire message.
  162. Similarly, ``decrypt`` can only be called once.
  163. * **assoc_len** : (*integer*) --
  164. (Only ``MODE_CCM``). Length of the associated data.
  165. If not specified, all associated data is buffered internally,
  166. which may represent a problem for very large messages.
  167. * **initial_value** : (*integer* or *bytes/bytearray/memoryview*) --
  168. (Only ``MODE_CTR``).
  169. The initial value for the counter. If not present, the cipher will
  170. start counting from 0. The value is incremented by one for each block.
  171. The counter number is encoded in big endian mode.
  172. * **counter** : (*object*) --
  173. Instance of ``Crypto.Util.Counter``, which allows full customization
  174. of the counter block. This parameter is incompatible to both ``nonce``
  175. and ``initial_value``.
  176. * **use_aesni** : (*boolean*) --
  177. Use Intel AES-NI hardware extensions (default: use if available).
  178. :Return: an AES object, of the applicable mode.
  179. """
  180. kwargs["add_aes_modes"] = True
  181. return _create_cipher(sys.modules[__name__], key, mode, *args, **kwargs)
  182. MODE_ECB = 1
  183. MODE_CBC = 2
  184. MODE_CFB = 3
  185. MODE_OFB = 5
  186. MODE_CTR = 6
  187. MODE_OPENPGP = 7
  188. MODE_CCM = 8
  189. MODE_EAX = 9
  190. MODE_SIV = 10
  191. MODE_GCM = 11
  192. MODE_OCB = 12
  193. # Size of a data block (in bytes)
  194. block_size = 16
  195. # Size of a key (in bytes)
  196. key_size = (16, 24, 32)