Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/Crypto/Cipher/AES.py: 71%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

125 statements  

1# 

2# Cipher/AES.py : AES 

3# 

4# =================================================================== 

5# The contents of this file are dedicated to the public domain. To 

6# the extent that dedication to the public domain is not available, 

7# everyone is granted a worldwide, perpetual, royalty-free, 

8# non-exclusive license to exercise all rights associated with the 

9# contents of this file for any purpose whatsoever. 

10# No rights are reserved. 

11# 

12# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 

13# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 

14# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 

15# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 

16# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 

17# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 

18# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 

19# SOFTWARE. 

20# =================================================================== 

21 

22from __future__ import annotations 

23 

24import sys 

25from typing import TYPE_CHECKING, Any, Literal, Optional, Union, overload 

26 

27from Crypto.Cipher import _create_cipher 

28from Crypto.Random import get_random_bytes 

29from Crypto.Util import _cpu_features 

30from Crypto.Util._raw_api import ( 

31 SmartPointer, 

32 VoidPointer, 

33 c_size_t, 

34 c_uint8_ptr_len, 

35 load_pycryptodome_raw_lib, 

36) 

37from Crypto.Util._typing import Buffer 

38 

39if TYPE_CHECKING: 

40 from Crypto.Cipher._mode_cbc import CbcMode 

41 from Crypto.Cipher._mode_ccm import CcmMode 

42 from Crypto.Cipher._mode_cfb import CfbMode 

43 from Crypto.Cipher._mode_ctr import CtrMode 

44 from Crypto.Cipher._mode_eax import EaxMode 

45 from Crypto.Cipher._mode_ecb import EcbMode 

46 from Crypto.Cipher._mode_gcm import GcmMode 

47 from Crypto.Cipher._mode_gcm_siv import GcmSivMode 

48 from Crypto.Cipher._mode_kw import KWMode 

49 from Crypto.Cipher._mode_kwp import KWPMode 

50 from Crypto.Cipher._mode_ocb import OcbMode 

51 from Crypto.Cipher._mode_ofb import OfbMode 

52 from Crypto.Cipher._mode_openpgp import OpenPgpMode 

53 from Crypto.Cipher._mode_siv import SivMode 

54 from Crypto.Cipher._mode_xts import XtsMode 

55 from Crypto.Util.Counter import CounterParams 

56 

57 

58MODE_ECB: Literal[1] = 1 #: Electronic Code Book (:ref:`ecb_mode`) 

59MODE_CBC: Literal[2] = 2 #: Cipher-Block Chaining (:ref:`cbc_mode`) 

60MODE_CFB: Literal[3] = 3 #: Cipher Feedback (:ref:`cfb_mode`) 

61MODE_OFB: Literal[5] = 5 #: Output Feedback (:ref:`ofb_mode`) 

62MODE_CTR: Literal[6] = 6 #: Counter mode (:ref:`ctr_mode`) 

63MODE_OPENPGP: Literal[7] = 7 #: OpenPGP mode (:ref:`openpgp_mode`) 

64MODE_CCM: Literal[8] = 8 #: Counter with CBC-MAC (:ref:`ccm_mode`) 

65MODE_EAX: Literal[9] = 9 #: :ref:`eax_mode` 

66MODE_SIV: Literal[10] = 10 #: Synthetic Initialization Vector (:ref:`siv_mode`) 

67MODE_GCM: Literal[11] = 11 #: Galois Counter Mode (:ref:`gcm_mode`) 

68MODE_OCB: Literal[12] = 12 #: Offset Code Book (:ref:`ocb_mode`) 

69MODE_KW: Literal[13] = 13 #: Key Wrap (:ref:`kw_mode`) 

70MODE_KWP: Literal[14] = 14 #: Key Wrap with Padding (:ref:`kwp_mode`) 

71MODE_GCM_SIV: Literal[15] = 15 #: AES-GCM-SIV (:ref:`gcm_siv_mode`) 

72MODE_XTS: Literal[16] = 16 #: XEX with ciphertext stealing, for storage (:ref:`xts_mode`) 

73 

74_cproto = """ 

75 int AES_start_operation(const uint8_t key[], 

76 size_t key_len, 

77 void **pResult); 

78 int AES_encrypt(const void *state, 

79 const uint8_t *in, 

80 uint8_t *out, 

81 size_t data_len); 

82 int AES_decrypt(const void *state, 

83 const uint8_t *in, 

84 uint8_t *out, 

85 size_t data_len); 

86 int AES_stop_operation(void *state); 

87 """ 

88 

89 

90# Load portable AES 

91_raw_aes_lib = load_pycryptodome_raw_lib("Crypto.Cipher._raw_aes", _cproto) 

92 

93 

94def _load_aes_hw(): 

95 """Return the (start, stop) functions of the AES implementation 

96 with the AES instructions of the CPU (AES-NI on x86, 

97 the ARMv8 Cryptography Extensions on AArch64), 

98 or None if the CPU does not have them.""" 

99 

100 if _cpu_features.have_aes_ni(): 

101 name, prefix = "Crypto.Cipher._raw_aesni", "AESNI" 

102 elif _cpu_features.have_aes_armv8(): 

103 name, prefix = "Crypto.Cipher._raw_aes_armv8", "AES_ARMV8" 

104 else: 

105 return None 

106 try: 

107 lib = load_pycryptodome_raw_lib(name, _cproto.replace("AES", prefix)) 

108 # The module may not have been compiled in 

109 except OSError: 

110 return None 

111 return (getattr(lib, prefix + "_start_operation"), getattr(lib, prefix + "_stop_operation")) 

112 

113 

114_raw_aes_hw = _load_aes_hw() 

115 

116 

117def _create_base_cipher(dict_parameters): 

118 """This method instantiates and returns a handle to a low-level 

119 base cipher. It will absorb named parameters in the process.""" 

120 

121 use_aesni = dict_parameters.pop("use_aesni", True) 

122 

123 try: 

124 key = dict_parameters.pop("key") 

125 except KeyError: 

126 raise TypeError("Missing 'key' parameter") 

127 

128 if len(key) not in key_size: 

129 raise ValueError("Incorrect AES key length (%d bytes)" % len(key)) 

130 

131 if use_aesni and _raw_aes_hw: 

132 start_operation, stop_operation = _raw_aes_hw 

133 else: 

134 start_operation = _raw_aes_lib.AES_start_operation 

135 stop_operation = _raw_aes_lib.AES_stop_operation 

136 

137 cipher = VoidPointer() 

138 key_ptr, key_len = c_uint8_ptr_len(key) 

139 result = start_operation(key_ptr, c_size_t(key_len), cipher.address_of()) 

140 if result: 

141 raise ValueError("Error %X while instantiating the AES cipher" % result) 

142 return SmartPointer(cipher.get(), stop_operation) 

143 

144 

145def _derive_Poly1305_key_pair(key, nonce): 

146 """Derive a tuple (r, s, nonce) for a Poly1305 MAC. 

147 

148 If nonce is ``None``, a new 16-byte nonce is generated. 

149 """ 

150 

151 if len(key) != 32: 

152 raise ValueError("Poly1305 with AES requires a 32-byte key") 

153 

154 if nonce is None: 

155 nonce = get_random_bytes(16) 

156 elif len(nonce) != 16: 

157 raise ValueError("Poly1305 with AES requires a 16-byte nonce") 

158 

159 s = new(key[:16], MODE_ECB).encrypt(nonce) 

160 return key[16:], s, nonce 

161 

162 

163@overload 

164def new(key: Buffer, mode: Literal[1], use_aesni: bool = ...) -> EcbMode: ... 

165 

166 

167@overload 

168def new(key: Buffer, mode: Literal[2], iv: Optional[Buffer] = ..., use_aesni: bool = ...) -> CbcMode: ... 

169 

170 

171@overload 

172def new(key: Buffer, mode: Literal[2], IV: Optional[Buffer] = ..., use_aesni: bool = ...) -> CbcMode: ... 

173 

174 

175@overload 

176def new( 

177 key: Buffer, mode: Literal[3], iv: Optional[Buffer] = ..., segment_size: int = ..., use_aesni: bool = ... 

178) -> CfbMode: ... 

179 

180 

181@overload 

182def new( 

183 key: Buffer, mode: Literal[3], IV: Optional[Buffer] = ..., segment_size: int = ..., use_aesni: bool = ... 

184) -> CfbMode: ... 

185 

186 

187@overload 

188def new(key: Buffer, mode: Literal[5], iv: Optional[Buffer] = ..., use_aesni: bool = ...) -> OfbMode: ... 

189 

190 

191@overload 

192def new(key: Buffer, mode: Literal[5], IV: Optional[Buffer] = ..., use_aesni: bool = ...) -> OfbMode: ... 

193 

194 

195@overload 

196def new( 

197 key: Buffer, 

198 mode: Literal[6], 

199 nonce: Optional[Buffer] = ..., 

200 initial_value: Union[int, Buffer] = ..., 

201 counter: CounterParams = ..., 

202 use_aesni: bool = ..., 

203 threads: int = ..., 

204) -> CtrMode: ... 

205 

206 

207@overload 

208def new(key: Buffer, mode: Literal[7], iv: Optional[Buffer] = ..., use_aesni: bool = ...) -> OpenPgpMode: ... 

209 

210 

211@overload 

212def new(key: Buffer, mode: Literal[7], IV: Optional[Buffer] = ..., use_aesni: bool = ...) -> OpenPgpMode: ... 

213 

214 

215@overload 

216def new( 

217 key: Buffer, 

218 mode: Literal[8], 

219 nonce: Optional[Buffer] = ..., 

220 mac_len: int = ..., 

221 assoc_len: int = ..., 

222 use_aesni: bool = ..., 

223) -> CcmMode: ... 

224 

225 

226@overload 

227def new( 

228 key: Buffer, mode: Literal[9], nonce: Optional[Buffer] = ..., mac_len: int = ..., use_aesni: bool = ... 

229) -> EaxMode: ... 

230 

231 

232@overload 

233def new(key: Buffer, mode: Literal[10], nonce: Optional[Buffer] = ..., use_aesni: bool = ...) -> SivMode: ... 

234 

235 

236@overload 

237def new( 

238 key: Buffer, 

239 mode: Literal[11], 

240 nonce: Optional[Buffer] = ..., 

241 mac_len: int = ..., 

242 use_aesni: bool = ..., 

243 threads: int = ..., 

244) -> GcmMode: ... 

245 

246 

247@overload 

248def new( 

249 key: Buffer, 

250 mode: Literal[12], 

251 nonce: Optional[Buffer] = ..., 

252 mac_len: int = ..., 

253 use_aesni: bool = ..., 

254 threads: int = ..., 

255) -> OcbMode: ... 

256 

257 

258@overload 

259def new(key: Buffer, mode: Literal[13], use_aesni: bool = ...) -> KWMode: ... 

260 

261 

262@overload 

263def new(key: Buffer, mode: Literal[14], use_aesni: bool = ...) -> KWPMode: ... 

264 

265 

266@overload 

267def new( 

268 key: Buffer, 

269 mode: Literal[15], 

270 nonce: Optional[Buffer] = ..., 

271 use_aesni: bool = ..., 

272 threads: int = ..., 

273) -> GcmSivMode: ... 

274 

275 

276@overload 

277def new(key: Buffer, mode: Literal[16], *, tweak: Buffer, use_aesni: bool = ...) -> XtsMode: ... 

278 

279 

280def new(key: Buffer, mode: int, *args: Any, **kwargs: Any) -> Any: 

281 """Create a new AES cipher. 

282 

283 Args: 

284 key(bytes/bytearray/memoryview): 

285 The secret key to use in the symmetric cipher. 

286 

287 It must be 16 (*AES-128)*, 24 (*AES-192*) or 32 (*AES-256*) bytes long. 

288 

289 For ``MODE_SIV`` only, it doubles to 32, 48, or 64 bytes. 

290 

291 For ``MODE_GCM_SIV`` only, it must be 16 or 32 bytes long. 

292 

293 For ``MODE_XTS`` only, it must be 32 or 64 bytes long: two AES-128 or 

294 AES-256 keys (concatenated), which must be different. 

295 mode (a ``MODE_*`` constant): 

296 The chaining mode to use for encryption or decryption. 

297 If in doubt, use ``MODE_GCM`` (with a random 12-byte ``nonce``). 

298 

299 Keyword Args: 

300 iv (bytes/bytearray/memoryview): 

301 (Only applicable for ``MODE_CBC``, ``MODE_CFB``, ``MODE_OFB``, 

302 and ``MODE_OPENPGP`` modes). 

303 

304 The initialization vector to use for encryption or decryption. 

305 

306 For ``MODE_CBC``, ``MODE_CFB``, and ``MODE_OFB`` it must be 16 bytes long. 

307 

308 For ``MODE_OPENPGP`` mode only, 

309 it must be 16 bytes long for encryption 

310 and 18 bytes for decryption (in the latter case, it is 

311 actually the *encrypted* IV which was prefixed to the ciphertext). 

312 

313 If not provided, a random byte string is generated (you must then 

314 read its value with the :attr:`iv` attribute). 

315 

316 nonce (bytes/bytearray/memoryview): 

317 (Only applicable for ``MODE_CCM``, ``MODE_EAX``, ``MODE_GCM``, 

318 ``MODE_SIV``, ``MODE_GCM_SIV``, ``MODE_OCB``, and ``MODE_CTR``). 

319 

320 A value that must never be reused for any other encryption done 

321 with this key (except possibly for ``MODE_SIV`` and ``MODE_GCM_SIV``, see below). 

322 

323 For ``MODE_EAX``, ``MODE_GCM`` and ``MODE_SIV`` there are no 

324 restrictions on its length (recommended: **16** bytes). 

325 

326 For ``MODE_CCM``, its length must be in the range **[7..13]**. 

327 Bear in mind that with CCM there is a trade-off between nonce 

328 length and maximum message size. Recommendation: **11** bytes. 

329 

330 For ``MODE_OCB``, its length must be in the range **[1..15]** 

331 (recommended: **15**). 

332 

333 For ``MODE_CTR``, its length must be in the range **[0..15]** 

334 (recommended: **8**). 

335 

336 For ``MODE_SIV``, the nonce is optional, if it is not specified, 

337 then no nonce is being used, which renders the encryption 

338 deterministic. 

339 

340 For ``MODE_GCM_SIV``, it must be **12** bytes long. Reusing a nonce 

341 only reveals if the same message was encrypted twice 

342 (with the same key, nonce and associated data). 

343 

344 If not provided, for modes other than ``MODE_SIV``, a random 

345 byte string of the recommended length is used (you must then 

346 read its value with the :attr:`nonce` attribute). 

347 

348 segment_size (integer): 

349 (Only ``MODE_CFB``).The number of **bits** the plaintext and ciphertext 

350 are segmented in. It must be a multiple of 8. 

351 If not specified, it will be assumed to be 8. 

352 

353 mac_len (integer): 

354 (Only ``MODE_EAX``, ``MODE_GCM``, ``MODE_OCB``, ``MODE_CCM``) 

355 Length of the authentication tag, in bytes. 

356 

357 It must be even and in the range **[4..16]**. 

358 The recommended value (and the default, if not specified) is **16**. 

359 

360 msg_len (integer): 

361 (Only ``MODE_CCM``). Length of the message to (de)cipher. 

362 If not specified, ``encrypt`` must be called with the entire message. 

363 Similarly, ``decrypt`` can only be called once. 

364 

365 assoc_len (integer): 

366 (Only ``MODE_CCM``). Length of the associated data. 

367 If not specified, all associated data is buffered internally, 

368 which may represent a problem for very large messages. 

369 

370 initial_value (integer or bytes/bytearray/memoryview): 

371 (Only ``MODE_CTR``). 

372 The initial value for the counter. If not present, the cipher will 

373 start counting from 0. The value is incremented by one for each block. 

374 The counter number is encoded in big endian mode. 

375 

376 counter (object): 

377 (Only ``MODE_CTR``). 

378 Instance of ``Crypto.Util.Counter``, which allows full customization 

379 of the counter block. This parameter is incompatible to both ``nonce`` 

380 and ``initial_value``. 

381 

382 use_aesni: (boolean): 

383 Use the AES instructions of the CPU (default: use if available): 

384 AES-NI on x86, or the Cryptography Extensions on 64-bit ARM. 

385 

386 threads (integer): 

387 (Only ``MODE_CTR``, ``MODE_GCM``, ``MODE_GCM_SIV`` and ``MODE_OCB``). 

388 The maximum number of threads used to encrypt or decrypt long data 

389 (default: 1, no extra threads). 

390 Use 0 for as many threads as the CPU cores available 

391 to this process. 

392 Each thread processes at least 1 MiB of a single call to 

393 ``encrypt()`` or ``decrypt()``: with shorter inputs, 

394 fewer threads are used, or none at all. 

395 For best results, do not exceed the number of physical cores. 

396 The output does not depend on the number of threads. 

397 

398 tweak (bytes/bytearray/memoryview): 

399 (Only ``MODE_XTS``, where it is mandatory). 

400 The value that identifies the data unit, 16 bytes long. 

401 For a sector number, use ``number.to_bytes(16, "little")``. 

402 

403 Returns: 

404 :ref:`A cipher object <aes_modes>`: Its class depends on ``mode``, 

405 see the table in :ref:`aes_modes`. 

406 """ 

407 

408 kwargs["add_aes_modes"] = True 

409 return _create_cipher(sys.modules[__name__], key, mode, *args, **kwargs) 

410 

411 

412#: Size of a data block (in bytes) 

413block_size: int = 16 

414#: The valid sizes of a key (in bytes) 

415key_size: tuple[int, int, int] = (16, 24, 32)