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