Skip to content

Commit dfb1852

Browse files
committed
BOM
1 parent e5c0ae0 commit dfb1852

File tree

22,381 files changed

+5712233
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

22,381 files changed

+5712233
-0
lines changed
Lines changed: 234 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,234 @@
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)
Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
1+
from typing import Dict, Optional, Tuple, Union, overload
2+
from typing_extensions import Literal
3+
4+
Buffer=bytes|bytearray|memoryview
5+
6+
from Crypto.Cipher._mode_ecb import EcbMode
7+
from Crypto.Cipher._mode_cbc import CbcMode
8+
from Crypto.Cipher._mode_cfb import CfbMode
9+
from Crypto.Cipher._mode_ofb import OfbMode
10+
from Crypto.Cipher._mode_ctr import CtrMode
11+
from Crypto.Cipher._mode_openpgp import OpenPgpMode
12+
from Crypto.Cipher._mode_ccm import CcmMode
13+
from Crypto.Cipher._mode_eax import EaxMode
14+
from Crypto.Cipher._mode_gcm import GcmMode
15+
from Crypto.Cipher._mode_siv import SivMode
16+
from Crypto.Cipher._mode_ocb import OcbMode
17+
18+
MODE_ECB: Literal[1]
19+
MODE_CBC: Literal[2]
20+
MODE_CFB: Literal[3]
21+
MODE_OFB: Literal[5]
22+
MODE_CTR: Literal[6]
23+
MODE_OPENPGP: Literal[7]
24+
MODE_CCM: Literal[8]
25+
MODE_EAX: Literal[9]
26+
MODE_SIV: Literal[10]
27+
MODE_GCM: Literal[11]
28+
MODE_OCB: Literal[12]
29+
30+
# MODE_ECB
31+
@overload
32+
def new(key: Buffer,
33+
mode: Literal[1],
34+
use_aesni : bool = ...) -> \
35+
EcbMode: ...
36+
37+
# MODE_CBC
38+
@overload
39+
def new(key: Buffer,
40+
mode: Literal[2],
41+
iv : Optional[Buffer] = ...,
42+
use_aesni : bool = ...) -> \
43+
CbcMode: ...
44+
45+
@overload
46+
def new(key: Buffer,
47+
mode: Literal[2],
48+
IV : Optional[Buffer] = ...,
49+
use_aesni : bool = ...) -> \
50+
CbcMode: ...
51+
52+
# MODE_CFB
53+
@overload
54+
def new(key: Buffer,
55+
mode: Literal[3],
56+
iv : Optional[Buffer] = ...,
57+
segment_size : int = ...,
58+
use_aesni : bool = ...) -> \
59+
CfbMode: ...
60+
61+
@overload
62+
def new(key: Buffer,
63+
mode: Literal[3],
64+
IV : Optional[Buffer] = ...,
65+
segment_size : int = ...,
66+
use_aesni : bool = ...) -> \
67+
CfbMode: ...
68+
69+
# MODE_OFB
70+
@overload
71+
def new(key: Buffer,
72+
mode: Literal[5],
73+
iv : Optional[Buffer] = ...,
74+
use_aesni : bool = ...) -> \
75+
OfbMode: ...
76+
77+
@overload
78+
def new(key: Buffer,
79+
mode: Literal[5],
80+
IV : Optional[Buffer] = ...,
81+
use_aesni : bool = ...) -> \
82+
OfbMode: ...
83+
84+
# MODE_CTR
85+
@overload
86+
def new(key: Buffer,
87+
mode: Literal[6],
88+
nonce : Optional[Buffer] = ...,
89+
initial_value : Union[int, Buffer] = ...,
90+
counter : Dict = ...,
91+
use_aesni : bool = ...) -> \
92+
CtrMode: ...
93+
94+
# MODE_OPENPGP
95+
@overload
96+
def new(key: Buffer,
97+
mode: Literal[7],
98+
iv : Optional[Buffer] = ...,
99+
use_aesni : bool = ...) -> \
100+
OpenPgpMode: ...
101+
102+
@overload
103+
def new(key: Buffer,
104+
mode: Literal[7],
105+
IV : Optional[Buffer] = ...,
106+
use_aesni : bool = ...) -> \
107+
OpenPgpMode: ...
108+
109+
# MODE_CCM
110+
@overload
111+
def new(key: Buffer,
112+
mode: Literal[8],
113+
nonce : Optional[Buffer] = ...,
114+
mac_len : int = ...,
115+
assoc_len : int = ...,
116+
use_aesni : bool = ...) -> \
117+
CcmMode: ...
118+
119+
# MODE_EAX
120+
@overload
121+
def new(key: Buffer,
122+
mode: Literal[9],
123+
nonce : Optional[Buffer] = ...,
124+
mac_len : int = ...,
125+
use_aesni : bool = ...) -> \
126+
EaxMode: ...
127+
128+
# MODE_GCM
129+
@overload
130+
def new(key: Buffer,
131+
mode: Literal[10],
132+
nonce : Optional[Buffer] = ...,
133+
use_aesni : bool = ...) -> \
134+
SivMode: ...
135+
136+
# MODE_SIV
137+
@overload
138+
def new(key: Buffer,
139+
mode: Literal[11],
140+
nonce : Optional[Buffer] = ...,
141+
mac_len : int = ...,
142+
use_aesni : bool = ...) -> \
143+
GcmMode: ...
144+
145+
# MODE_OCB
146+
@overload
147+
def new(key: Buffer,
148+
mode: Literal[12],
149+
nonce : Optional[Buffer] = ...,
150+
mac_len : int = ...,
151+
use_aesni : bool = ...) -> \
152+
OcbMode: ...
153+
154+
155+
block_size: int
156+
key_size: Tuple[int, int, int]

0 commit comments

Comments
 (0)