Debian Codegraph @

lib/Crypto/Cipher/AES.py

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