1PYCRYPTODOME(1) PyCryptodome PYCRYPTODOME(1)
2
3
4
6 pycryptodome - PyCryptodome Documentation .SH PYCRYPTODOME
7
8 PyCryptodome is a self-contained Python package of low-level crypto‐
9 graphic primitives.
10
11 It supports Python 2.7, Python 3.5 and newer, and PyPy.
12
13 The installation procedure depends on the package you want the library
14 to be in. PyCryptodome can be used as:
15
16 1. an almost drop-in replacement for the old PyCrypto library. You in‐
17 stall it with:
18
19 pip install pycryptodome
20
21 In this case, all modules are installed under the Crypto package.
22
23 One must avoid having both PyCrypto and PyCryptodome installed at
24 the same time, as they will interfere with each other.
25
26 This option is therefore recommended only when you are sure that the
27 whole application is deployed in a virtualenv.
28
29 2. a library independent of the old PyCrypto. You install it with:
30
31 pip install pycryptodomex
32
33 In this case, all modules are installed under the Cryptodome pack‐
34 age. PyCrypto and PyCryptodome can coexist.
35
36 For faster public key operations in Unix, you should install GMP in
37 your system.
38
39 PyCryptodome is a fork of PyCrypto. It brings the following enhance‐
40 ments with respect to the last official version of PyCrypto (2.6.1):
41
42 • Authenticated encryption modes (GCM, CCM, EAX, SIV, OCB)
43
44 • Accelerated AES on Intel platforms via AES-NI
45
46 • First class support for PyPy
47
48 • Elliptic curves cryptography (NIST P-256, P-384 and P-521 curves
49 only)
50
51 • Better and more compact API (nonce and iv attributes for ciphers, au‐
52 tomatic generation of random nonces and IVs, simplified CTR cipher
53 mode, and more)
54
55 • SHA-3 (including SHAKE and cSHAKE XOFs), truncated SHA-512 and BLAKE2
56 hash algorithms
57
58 • Salsa20 and ChaCha20/XChaCha20 stream ciphers
59
60 • Poly1305 MAC
61
62 • ChaCha20-Poly1305 and XChaCha20-Poly1305 authenticated ciphers
63
64 • scrypt, bcrypt and HKDF derivation functions
65
66 • Deterministic (EC)DSA
67
68 • Password-protected PKCS#8 key containers
69
70 • Shamir's Secret Sharing scheme
71
72 • Random numbers get sourced directly from the OS (and not from a
73 CSPRNG in userspace)
74
75 • Simplified install process, including better support for Windows
76
77 • Cleaner RSA and DSA key generation (largely based on FIPS 186-4)
78
79 • Major clean ups and simplification of the code base
80
81 PyCryptodome is not a wrapper to a separate C library like OpenSSL. To
82 the largest possible extent, algorithms are implemented in pure Python.
83 Only the pieces that are extremely critical to performance (e.g. block
84 ciphers) are implemented as C extensions.
85
86 For more information, see the homepage.
87
88 For security issues, please send an email to security@pycryptodome.org.
89
90 All the code can be downloaded from GitHub.
91
93 This page lists the low-level primitives that PyCryptodome provides.
94
95 You are expected to have a solid understanding of cryptography and se‐
96 curity engineering to successfully use them.
97
98 You must also be able to recognize that some primitives are obsolete
99 (e.g. TDES) or even unsecure (RC4). They are provided only to enable
100 backward compatibility where required by the applications.
101
102 A list of useful resources in that area can be found on Matthew Green's
103 blog.
104
105 • Symmetric ciphers:
106
107 • AES
108
109 • Single and Triple DES (legacy)
110
111 • CAST-128 (legacy)
112
113 • RC2 (legacy)
114
115 • Traditional modes of operations for symmetric ciphers:
116
117 • ECB
118
119 • CBC
120
121 • CFB
122
123 • OFB
124
125 • CTR
126
127 • OpenPGP (a variant of CFB, RFC4880)
128
129 • Authenticated Encryption:
130
131 • CCM (AES only)
132
133 • EAX
134
135 • GCM (AES only)
136
137 • SIV (AES only)
138
139 • OCB (AES only)
140
141 • ChaCha20-Poly1305
142
143 • Stream ciphers:
144
145 • Salsa20
146
147 • ChaCha20
148
149 • RC4 (legacy)
150
151 • Cryptographic hashes:
152
153 • SHA-1
154
155 • SHA-2 hashes (224, 256, 384, 512, 512/224, 512/256)
156
157 • SHA-3 hashes (224, 256, 384, 512) and XOFs (SHAKE128, SHAKE256)
158
159 • Keccak (original submission to SHA-3)
160
161 • BLAKE2b and BLAKE2s
162
163 • RIPE-MD160 (legacy)
164
165 • MD5 (legacy)
166
167 • Message Authentication Codes (MAC):
168
169 • HMAC
170
171 • CMAC
172
173 • Poly1305
174
175 • Asymmetric key generation:
176
177 • RSA
178
179 • ECC (NIST P-256, P-384 and P-521 curve only)
180
181 • DSA
182
183 • ElGamal (legacy)
184
185 • Export and import format for asymmetric keys:
186
187 • PEM (clear and encrypted)
188
189 • PKCS#8 (clear and encrypted)
190
191 • ASN.1 DER
192
193 • Asymmetric ciphers:
194
195 • PKCS#1 (RSA)
196
197 • RSAES-PKCS1-v1_5
198
199 • RSAES-OAEP
200
201 • Asymmetric digital signatures:
202
203 • PKCS#1 (RSA)
204
205 • RSASSA-PKCS1-v1_5
206
207 • RSASSA-PSS
208
209 • (EC)DSA
210
211 • Nonce-based (FIPS 186-3)
212
213 • Deterministic (RFC6979)
214
215 • Key derivation:
216
217 • PBKDF2
218
219 • scrypt
220
221 • HKDF
222
223 • PBKDF1 (legacy)
224
225 • Other cryptographic protocols:
226
227 • Shamir Secret Sharing
228
229 • Padding
230
231 • PKCS#7
232
233 • ISO-7816
234
235 • X.923
236
238 The installation procedure depends on the package you want the library
239 to be in. PyCryptodome can be used as:
240
241 1. An almost drop-in replacement for the old PyCrypto library. You
242 install it with:
243
244 pip install pycryptodome
245
246 In this case, all modules are installed under the Crypto package.
247 You can test everything is right with:
248
249 pip install pycryptodome-test-vectors
250 python -m Crypto.SelfTest
251
252 One must avoid having both PyCrypto and PyCryptodome installed at
253 the same time, as they will interfere with each other. This op‐
254 tion is therefore recommended only when you are sure that the
255 whole application is deployed in a virtualenv.
256
257 2. A library independent of the old PyCrypto. You install it with:
258
259 pip install pycryptodomex
260
261 You can test everything is right with:
262
263 pip install pycryptodome-test-vectors
264 python -m Cryptodome.SelfTest
265
266 In this case, all modules are installed under the Cryptodome
267 package. The old PyCrypto and PyCryptodome can coexist.
268
269 NOTE:
270 If you intend to run PyCryptodome with Python 2.7 under Windows, you
271 must first install the Microsoft Visual C++ 2015 Redistributable.
272 That is not necessary if you use Python 3.
273
274 The procedures below go a bit more in detail, by explaining how to
275 setup the environment for compiling the C extensions for each OS, and
276 how to install the GMP library.
277
278 Compiling in Linux Ubuntu
279 NOTE:
280 If you want to install under the Crypto package, replace below py‐
281 cryptodomex with pycryptodome.
282
283 For Python 2.x:
284
285 $ sudo apt-get install build-essential python-dev
286 $ pip install pycryptodomex
287 $ pip install pycryptodome-test-vectors
288 $ python -m Cryptodome.SelfTest
289
290 For Python 3.x:
291
292 $ sudo apt-get install build-essential python3-dev
293 $ pip install pycryptodomex
294 $ pip install pycryptodome-test-vectors
295 $ python3 -m Cryptodome.SelfTest
296
297 For PyPy:
298
299 $ sudo apt-get install build-essential pypy-dev
300 $ pip install pycryptodomex
301 $ pip install pycryptodome-test-vectors
302 $ pypy -m Cryptodome.SelfTest
303
304 Compiling in Linux Fedora
305 NOTE:
306 If you want to install under the Crypto package, replace below py‐
307 cryptodomex with pycryptodome.
308
309 For Python 2.x:
310
311 $ sudo yum install gcc gmp python-devel
312 $ pip install pycryptodomex
313 $ pip install pycryptodome-test-vectors
314 $ python -m Cryptodome.SelfTest
315
316 For Python 3.x:
317
318 $ sudo yum install gcc gmp python3-devel
319 $ pip install pycryptodomex
320 $ pip install pycryptodome-test-vectors
321 $ python3 -m Cryptodome.SelfTest
322
323 For PyPy:
324
325 $ sudo yum install gcc gmp pypy-devel
326 $ pip install pycryptodomex
327 $ pip install pycryptodome-test-vectors
328 $ pypy -m Cryptodome.SelfTest
329
330 Windows (from sources)
331 NOTE:
332 If you want to install under the Crypto package, replace below py‐
333 cryptodomex with pycryptodome.
334
335 Windows does not come with a C compiler like most Unix systems. The
336 simplest way to compile the PyCryptodome extensions from source code is
337 to install the minimum set of Visual Studio components freely made
338 available by Microsoft.
339
340 1. [Once only] Download Build Tools for Visual Studio 2019. In the in‐
341 staller, select the C++ build tools, the Windows 10 SDK, and the
342 latest version of MSVC v142 x64/x86 build tools.
343
344 2. Compile and install PyCryptodome:
345
346 > pip install pycryptodomex --no-binary :all:
347
348 3. To make sure everything work fine, run the test suite:
349
350 > pip install pycryptodome-test-vectors
351 > python -m Cryptodome.SelfTest
352
353 Documentation
354 Project documentation is written in reStructuredText and it is stored
355 under Doc/src. To publish it as HTML files, you need to install sphinx
356 and use:
357
358 > make -C Doc/ html
359
360 It will then be available under Doc/_build/html/.
361
362 PGP verification
363 All source packages and wheels on PyPI are cryptographically signed.
364 They can be verified with the following PGP key:
365
366 -----BEGIN PGP PUBLIC KEY BLOCK-----
367
368 mQINBFTXjPgBEADc3j7vnma9MXRshBPPXXenVpthQD6lrF/3XaBT2RptSf/viOD+
369 tz85du5XVp+r0SYYGeMNJCQ9NsztxblN/lnKgkfWRmSrB+V6QGS+e3bR5d9OIxzN
370 7haPxBnyRj//hCT/kKis6fa7N9wtwKBBjbaSX+9vpt7Rrt203sKfcChA4iR3EG89
371 TNQoc/kGGmwk/gyjfU38726v0NOhMKJp2154iQQVZ76hTDk6GkOYHTcPxdkAj4jS
372 Dd74M9sOtoOlyDLHOLcWNnlWGgZjtz0z0qSyFXRSuOfggTxrepWQgKWXXzgVB4Jo
373 0bhmXPAV8vkX5BoG6zGkYb47NGGvknax6jCvFYTCp1sOmVtf5UTVKPplFm077tQg
374 0KZNAvEQrdWRIiQ1cCGCoF2Alex3VmVdefHOhNmyY7xAlzpP0c8z1DsgZgMnytNn
375 GPusWeqQVijRxenl+lyhbkb9ZLDq7mOkCRXSze9J2+5aLTJbJu3+Wx6BEyNIHP/f
376 K3E77nXvC0oKaYTbTwEQSBAggAXP+7oQaA0ea2SLO176xJdNfC5lkQEtMMSZI4gN
377 iSqjUxXW2N5qEHHex1atmTtk4W9tQEw030a0UCxzDJMhD0aWFKq7wOxoCQ1q821R
378 vxBH4cfGWdL/1FUcuCMSUlc6fhTM9pvMXgjdEXcoiLSTdaHuVLuqmF/E0wARAQAB
379 tB9MZWdyYW5kaW4gPGhlbGRlcmlqc0BnbWFpbC5jb20+iQI4BBMBAgAiBQJU14z4
380 AhsDBgsJCAcDAgYVCAIJCgsEFgIDAQIeAQIXgAAKCRDabO+N4RaZEn7IEACpApha
381 vRwPB+Dv87aEyVmjZ96Nb3mxHdeP2uSmUxAODzoB5oJJ1QL6HRxEVlU8idjdf73H
382 DX39ZC7izD+oYIve9sNwTbKqJCZaTxlTDdgSF1N57eJOlELAy+SqpHtaMJPk7SfJ
383 l/iYoUYxByPLZU1wDwZEDNzt9RCGy3bd/vF/AxWjdUJJPh3E4j5hswvIGSf8/Tp3
384 MDROU1BaNBOd0CLvBHok8/xavwO6Dk/fE4hJhd5uZcEPtd1GJcPq51z2yr7PGUcb
385 oERsKZyG8cgfd7j8qoTd6jMIW6fBVHdxiMxW6/Z45X/vVciQSzzEl/yjPUW42kyr
386 Ib6M16YmnDzp8bl4NNFvvR9uWvOdUkep2Bi8s8kBMJ7G9rHHJcdVy/tP1ECS9Bse
387 hN4v5oJJ4v5mM/MiWRGKykZULWklonpiq6CewYkmXQDMRnjGXhjCWrB6LuSIkIXd
388 gKvDNpJ8yEhAfmpvA4I3laMoof/tSZ7ZuyLSZGLKl6hoNIB13HCn4dnjNBeaXCWX
389 pThgeOWxV6u1fhz4CeC1Hc8WOYr8S7G8P10Ji6owOcj/a1QuCW8XDB2omCTXlhFj
390 zpC9dX8HgmUVnbPNiMjphihbKXoOcunRx4ZvqIa8mnTbI4tHtR0K0tI4MmbpcVOZ
391 8IFJ0nZJXuZiL57ijLREisPYmHfBHAgmh1j/W7kCDQRU14z4ARAA3QATRgvOSYFh
392 nJOnIz6PO3G9kXWjJ8wvp3yE1/PwwTc3NbVUSNCW14xgM2Ryhn9NVh8iEGtPGmUP
393 4vu7rvuLC2rBs1joBTyqf0mDghlZrb5ZjXv5LcG9SA6FdAXRU6T+b1G2ychKkhEh
394 d/ulLw/TKLds9zHhE+hkAagLQ5jqjcQN0iX5EYaOukiPUGmnd9fOEGi9YMYtRdrH
395 +3bZxUpsRStLBWJ6auY7Bla8NJOhaWpr5p/ls+mnDWoqf+tXCCps1Da/pfHKYDFc
396 2VVdyM/VfNny9eaczYpnj5hvIAACWChgGDBwxPh2DGdUfiQi/QqrK96+F7ulqz6V
397 2exX4CL0cPv5fUpQqSU/0R5WApM9bl2+wljFhoCXlydU9HNn+0GatGzEoo3yrV/m
398 PXv7d6NdZxyOqgxu/ai/z++F2pWUXSBxZN3Gv28boFKQhmtthTcFudNUtQOchhn8
399 Pf/ipVISqrsZorTx9Qx4fPScEWjwbh84Uz20bx0sQs1oYcek2YG5RhEdzqJ6W78R
400 S/dbzlNYMXGdkxB6C63m8oiGvw0hdN/iGVqpNAoldFmjnFqSgKpyPwfLmmdstJ6f
401 xFZdGPnKexCpHbKr9fg50jZRenIGai79qPIiEtCZHIdpeemSrc7TKRPV3H2aMNfG
402 L5HTqcyaM2+QrMtHPMoOFzcjkigLimMAEQEAAYkCHwQYAQIACQUCVNeM+AIbDAAK
403 CRDabO+N4RaZEo7lD/45J6z2wbL8aIudGEL0aY3hfmW3qrUyoHgaw35KsOY9vZwb
404 cZuJe0RlYptOreH/NrbR5SXODfhd2sxYyyvXBOuZh9i7OOBsrAd5UE01GCvToPwh
405 7IpMV3GSSAB4P8XyJh20tZqiZOYKhmbf29gUDzqAI6GzUa0U8xidUKpW2zqYGZjp
406 wk3RI1fS7tyi/0N8B9tIZF48kbvpFDAjF8w7NSCrgRquAL7zJZIG5o5zXJM/ffF3
407 67Dnz278MbifdM/HJ+Tj0R0Uvvki9Z61nT653SoUgvILQyC72XI+x0+3GQwsE38a
408 5aJNZ1NBD3/v+gERQxRfhM5iLFLXK0Xe4K2XFM1g0yN4L4bQPbhSCq88g9Dhmygk
409 XPbBsrK0NKPVnyGyUXM0VpgRbot11hxx02jC3HxS1nlLF+oQdkKFzJAMOU7UbpX/
410 oO+286J1FmpG+fihIbvp1Quq48immtnzTeLZbYCsG4mrM+ySYd0Er0G8TBdAOTiN
411 3zMbGX0QOO2fOsJ1d980cVjHn5CbAo8C0A/4/R2cXAfpacbvTiNq5BVk9NKa2dNb
412 kmnTStP2qILWmm5ASXlWhOjWNmptvsUcK+8T+uQboLioEv19Ob4j5Irs/OpOuP0K
413 v4woCi9+03HMS42qGSe/igClFO3+gUMZg9PJnTJhuaTbytXhUBgBRUPsS+lQAQ==
414 =DpoI
415 -----END PGP PUBLIC KEY BLOCK-----
416
418 PyCryptodome exposes almost the same API as the old PyCrypto so that
419 most applications will run unmodified. However, a very few breaks in
420 compatibility had to be introduced for those parts of the API that rep‐
421 resented a security hazard or that were too hard to maintain.
422
423 Specifically, for public key cryptography:
424
425 • The following methods from public key objects (RSA, DSA, ElGamal)
426 have been removed:
427
428 • sign()
429
430 • verify()
431
432 • encrypt()
433
434 • decrypt()
435
436 • blind()
437
438 • unblind()
439
440 Applications should be updated to use instead:
441
442 • Crypto.Cipher.PKCS1_OAEP for encrypting using RSA.
443
444 • Crypto.Signature.pkcs1_15 or Crypto.Signature.pss for signing using
445 RSA.
446
447 • Crypto.Signature.DSS for signing using DSA.
448
449 • Method: generate() for public key modules does not accept the
450 progress_func parameter anymore.
451
452 • Ambiguous method size from RSA, DSA and ElGamal key objects have been
453 removed. Instead, use methods size_in_bytes() and size_in_bits() and
454 check the documentation.
455
456 • The 3 public key object types (RSA, DSA, ElGamal) are now unpickable.
457 You must use the export_key() method of each key object and select a
458 good output format: for private keys that means a good password-based
459 encryption scheme.
460
461 • Removed attribute Crypto.PublicKey.RSA.algorithmIdentifier.
462
463 • Removed Crypto.PublicKey.RSA.RSAImplementation (which should have
464 been private in the first place). Same for Crypto.Pub‐
465 licKey.DSA.DSAImplementation.
466
467 For symmetric key cryptography:
468
469 • Symmetric ciphers do not have ECB as default mode anymore. ECB is not
470 semantically secure and it exposes correlation across blocks. An ex‐
471 pression like AES.new(key) will now fail. If ECB is the desired mode,
472 one has to explicitly use AES.new(key, AES.MODE_ECB).
473
474 • Crypto.Cipher.DES3 does not allow keys that degenerate to Single DES.
475
476 • Parameter segment_size cannot be 0 for the CFB mode.
477
478 • Parameters disabled_shortcut and overflow cannot be passed anymore to
479 Crypto.Util.Counter.new. Parameter allow_wraparound is ignored
480 (counter block wraparound will always be checked).
481
482 • The counter parameter of a CTR mode cipher must be generated via
483 Crypto.Util.Counter. It cannot be a generic callable anymore.
484
485 • Keys for Crypto.Cipher.ARC2, Crypto.Cipher.ARC4 and Crypto.Ci‐
486 pher.Blowfish must be at least 40 bits long (still very weak).
487
488 The following packages, modules and functions have been removed:
489
490 • Crypto.Random.OSRNG, Crypto.Util.winrandom and Crypto.Random.rand‐
491 pool. You should use Crypto.Random only.
492
493 • Crypto.Cipher.XOR. If you just want to XOR data, use
494 Crypto.Util.strxor.
495
496 • Crypto.Hash.new. Use Crypto.Hash.<algorithm>.new() instead.
497
498 • Crypto.Protocol.AllOrNothing
499
500 • Crypto.Protocol.Chaffing
501
502 • Crypto.Util.number.getRandomNumber
503
504 • Crypto.pct_warnings
505
506 Others:
507
508 • Support for any Python version older than 2.6 is dropped.
509
511 Crypto.Cipher package
512 Introduction
513 The Crypto.Cipher package contains algorithms for protecting the confi‐
514 dentiality of data.
515
516 There are three types of encryption algorithms:
517
518 1. Symmetric ciphers: all parties use the same key, for both decrypting
519 and encrypting data. Symmetric ciphers are typically very fast and
520 can process very large amount of data.
521
522 2. Asymmetric ciphers: senders and receivers use different keys.
523 Senders encrypt with public keys (non-secret) whereas receivers de‐
524 crypt with private keys (secret). Asymmetric ciphers are typically
525 very slow and can process only very small payloads. Example: oaep.
526
527 3. Hybrid ciphers: the two types of ciphers above can be combined in a
528 construction that inherits the benefits of both. An asymmetric ci‐
529 pher is used to protect a short-lived symmetric key, and a symmetric
530 cipher (under that key) encrypts the actual message.
531
532 API principles
533 [image] Generic state diagram for a cipher object.UNINDENT
534
535 The base API of a cipher is fairly simple:
536
537 • You instantiate a cipher object by calling the new() function from
538 the relevant cipher module (e.g. Crypto.Cipher.AES.new()). The first
539 parameter is always the cryptographic key; its length depends on the
540 particular cipher. You can (and sometimes must) pass additional ci‐
541 pher- or mode-specific parameters to new() (such as a nonce or a mode
542 of operation).
543
544 • For encrypting data, you call the encrypt() method of the cipher ob‐
545 ject with the plaintext. The method returns the piece of ciphertext.
546 Alternatively, with the output parameter you can specify a pre-allo‐
547 cated buffer for the result.
548
549 For most algorithms, you may call encrypt() multiple times (i.e. once
550 for each piece of plaintext).
551
552 • For decrypting data, you call the decrypt() method of the cipher ob‐
553 ject with the ciphertext. The method returns the piece of plaintext.
554 The output parameter can be passed here too.
555
556 For most algorithms, you may call decrypt() multiple times
557 (i.e. once for each piece of ciphertext).
558
559 NOTE:
560 Plaintexts and ciphertexts (input/output) can only be bytes, bytear‐
561 ray or memoryview. In Python 3, you cannot pass strings. In Python
562 2, you cannot pass Unicode strings.
563
564 Often, the sender has to deliver to the receiver other data in addition
565 to ciphertext alone (e.g. initialization vectors or nonces, MAC tags,
566 etc).
567
568 This is a basic example:
569
570 >>> from Crypto.Cipher import Salsa20
571 >>>
572 >>> key = b'0123456789012345'
573 >>> cipher = Salsa20.new(key)
574 >>> ciphertext = cipher.encrypt(b'The secret I want to send.')
575 >>> ciphertext += cipher.encrypt(b'The second part of the secret.')
576 >>> print cipher.nonce # A byte string you must send to the receiver too
577
578 Symmetric ciphers
579 There are two types of symmetric ciphers:
580
581 • Stream ciphers: the most natural kind of ciphers: they encrypt data
582 one byte at a time. See chacha20 and salsa20.
583
584 • Block ciphers: ciphers that can only operate on a fixed amount of
585 data. The most important block cipher is aes, which has a block size
586 of 128 bits (16 bytes).
587
588 In general, a block cipher is mostly useful only together with a mode
589 of operation, which allows one to encrypt a variable amount of data.
590 Some modes (like CTR) effectively turn a block cipher into a stream
591 cipher.
592
593 The widespread consensus is that ciphers that provide only confiden‐
594 tiality, without any form of authentication, are undesirable. Instead,
595 primitives have been defined to integrate symmetric encryption and au‐
596 thentication (MAC). For instance:
597
598 • Modern modes of operation for block ciphers (like GCM).
599
600 • Stream ciphers paired with a MAC function, like chacha20_poly1305.
601
602 Classic modes of operation for symmetric block ciphers
603 A block cipher uses a symmetric key to encrypt data of fixed and very
604 short length (the block size), such as 16 bytes for AES. In order to
605 cope with data of arbitrary length, the cipher must be combined with a
606 mode of operation.
607
608 You create a cipher object with the new() function in the relevant mod‐
609 ule under Crypto.Cipher:
610
611 1. the first parameter is always the cryptographic key (a byte string)
612
613 2. the second parameter is always the constant that selects the desired
614 mode of operation
615
616 Constants for each mode of operation are defined at the module level
617 for each algorithm. Their name starts with MODE_, for instance
618 Crypto.Cipher.AES.MODE_CBC. Note that not all ciphers support all
619 modes.
620
621 For instance:
622
623 >>> from Crypto.Cipher import AES
624 >>> from Crypto.Random import get_random_bytes
625 >>>
626 >>> key = get_random_bytes(16)
627 >>> cipher = AES.new(key, AES.MODE_CBC)
628 >>>
629 >>> # You can now use use cipher to encrypt or decrypt...
630
631 The state machine for a cipher configured with a classic mode is:
632 [image] Generic state diagram for a cipher object.UNINDENT
633
634 What follows is a list of classic modes of operation: they all pro‐
635 vide confidentiality but not data integrity (unlike modern AEAD
636 modes, which are described in another section).
637
638 ECB mode
639 Electronic CodeBook. The most basic but also the weakest mode of oper‐
640 ation. Each block of plaintext is encrypted independently of any other
641 block.
642
643 WARNING:
644 The ECB mode should not be used because it is semantically insecure.
645 For one, it exposes correlation between blocks.
646
647 The new() function at the module level under Crypto.Cipher instantiates
648 a new ECB cipher object for the relevant base algorithm. In the fol‐
649 lowing definition, <algorithm> could be AES:
650
651 Crypto.Cipher.<algorithm>.new(key, mode)
652 Create a new ECB object, using <algorithm> as the base block ci‐
653 pher.
654
655 Parameters
656
657 • key (bytes) -- the cryptographic key
658
659 • mode -- the constant Crypto.Cipher.<algorithm>.MODE_ECB
660
661 Returns
662 an ECB cipher object
663
664 The method encrypt() (and likewise decrypt()) of an ECB cipher object
665 expects data to have length multiple of the block size (e.g. 16 bytes
666 for AES). You might need to use Crypto.Util.Padding to align the
667 plaintext to the right boundary.
668
669 CBC mode
670 Ciphertext Block Chaining, defined in NIST SP 800-38A, section 6.2. It
671 is a mode of operation where each plaintext block gets XOR-ed with the
672 previous ciphertext block prior to encryption.
673
674 The new() function at the module level under Crypto.Cipher instantiates
675 a new CBC cipher object for the relevant base algorithm. In the fol‐
676 lowing definition, <algorithm> could be AES:
677
678 Crypto.Cipher.<algorithm>.new(key, mode, *, iv=None)
679 Create a new CBC object, using <algorithm> as the base block ci‐
680 pher.
681
682 Parameters
683
684 • key (bytes) -- the cryptographic key
685
686 • mode -- the constant Crypto.Cipher.<algorithm>.MODE_CBC
687
688 • iv (bytes) -- the Initialization Vector. A piece of
689 data unpredictable to adversaries. It is as long as
690 the block size (e.g. 16 bytes for AES). If not
691 present, the library creates a random IV value.
692
693 Returns
694 a CBC cipher object
695
696 The method encrypt() (and likewise decrypt()) of a CBC cipher object
697 expects data to have length multiple of the block size (e.g. 16 bytes
698 for AES). You might need to use Crypto.Util.Padding to align the
699 plaintext to the right boundary.
700
701 A CBC cipher object has a read-only attribute iv, holding the Initial‐
702 ization Vector (bytes).
703
704 Example (encryption):
705
706 >>> import json
707 >>> from base64 import b64encode
708 >>> from Crypto.Cipher import AES
709 >>> from Crypto.Util.Padding import pad
710 >>> from Crypto.Random import get_random_bytes
711 >>>
712 >>> data = b"secret"
713 >>> key = get_random_bytes(16)
714 >>> cipher = AES.new(key, AES.MODE_CBC)
715 >>> ct_bytes = cipher.encrypt(pad(data, AES.block_size))
716 >>> iv = b64encode(cipher.iv).decode('utf-8')
717 >>> ct = b64encode(ct_bytes).decode('utf-8')
718 >>> result = json.dumps({'iv':iv, 'ciphertext':ct})
719 >>> print(result)
720 '{"iv": "bWRHdzkzVDFJbWNBY0EwSmQ1UXFuQT09", "ciphertext": "VDdxQVo3TFFCbXIzcGpYa1lJbFFZQT09"}'
721
722 Example (decryption):
723
724 >>> import json
725 >>> from base64 import b64decode
726 >>> from Crypto.Cipher import AES
727 >>> from Crypto.Util.Padding import unpad
728 >>>
729 >>> # We assume that the key was securely shared beforehand
730 >>> try:
731 >>> b64 = json.loads(json_input)
732 >>> iv = b64decode(b64['iv'])
733 >>> ct = b64decode(b64['ciphertext'])
734 >>> cipher = AES.new(key, AES.MODE_CBC, iv)
735 >>> pt = unpad(cipher.decrypt(ct), AES.block_size)
736 >>> print("The message was: ", pt)
737 >>> except ValueError, KeyError:
738 >>> print("Incorrect decryption")
739
740 CTR mode
741 CounTeR mode, defined in NIST SP 800-38A, section 6.5 and Appendix B.
742 This mode turns the block cipher into a stream cipher. Each byte of
743 plaintext is XOR-ed with a byte taken from a keystream: the result is
744 the ciphertext. The keystream is generated by encrypting a sequence of
745 counter blocks with ECB.
746 [image]
747
748 A counter block is exactly as long as the cipher block size (e.g. 16
749 bytes for AES). It consists of the concatenation of two pieces:
750
751 1. a fixed nonce, set at initialization.
752
753 2. a variable counter, which gets increased by 1 for any subsequent
754 counter block. The counter is big endian encoded.
755
756 The new() function at the module level under Crypto.Cipher instantiates
757 a new CTR cipher object for the relevant base algorithm. In the fol‐
758 lowing definition, <algorithm> could be AES:
759
760 Crypto.Cipher.<algorithm>.new(key, mode, *, nonce=None, ini‐
761 tial_value=None, counter=None)
762 Create a new CTR object, using <algorithm> as the base block ci‐
763 pher.
764
765 Parameters
766
767 • key (bytes) -- the cryptographic key
768
769 • mode -- the constant Crypto.Cipher.<algorithm>.MODE_CTR
770
771 • nonce (bytes) -- the value of the fixed nonce. It must
772 be unique for the combination message/key. Its length
773 varies from 0 to the block size minus 1. If not
774 present, the library creates a random nonce of length
775 equal to block size/2.
776
777 • initial_value (integer or bytes) -- the value of the
778 counter for the first counter block. It can be either
779 an integer or bytes (which is the same integer, just
780 big endian encoded). If not specified, the counter
781 starts at 0.
782
783 • counter -- a custom counter object created with
784 Crypto.Util.Counter.new(). This allows the definition
785 of a more complex counter block.
786
787 Returns
788 a CTR cipher object
789
790 The methods encrypt() and decrypt() of a CTR cipher object accept data
791 of any length (i.e. padding is not needed). Both raise an OverflowEr‐
792 ror exception as soon as the counter wraps around to repeat the origi‐
793 nal value.
794
795 The CTR cipher object has a read-only attribute nonce (bytes).
796
797 Example (encryption):
798
799 >>> import json
800 >>> from base64 import b64encode
801 >>> from Crypto.Cipher import AES
802 >>> from Crypto.Random import get_random_bytes
803 >>>
804 >>> data = b"secret"
805 >>> key = get_random_bytes(16)
806 >>> cipher = AES.new(key, AES.MODE_CTR)
807 >>> ct_bytes = cipher.encrypt(data)
808 >>> nonce = b64encode(cipher.nonce).decode('utf-8')
809 >>> ct = b64encode(ct_bytes).decode('utf-8')
810 >>> result = json.dumps({'nonce':nonce, 'ciphertext':ct})
811 >>> print(result)
812 {"nonce": "XqP8WbylRt0=", "ciphertext": "Mie5lqje"}
813
814 Example (decryption):
815
816 >>> import json
817 >>> from base64 import b64decode
818 >>> from Crypto.Cipher import AES
819 >>>
820 >>> # We assume that the key was securely shared beforehand
821 >>> try:
822 >>> b64 = json.loads(json_input)
823 >>> nonce = b64decode(b64['nonce'])
824 >>> ct = b64decode(b64['ciphertext'])
825 >>> cipher = AES.new(key, AES.MODE_CTR, nonce=nonce)
826 >>> pt = cipher.decrypt(ct)
827 >>> print("The message was: ", pt)
828 >>> except ValueError, KeyError:
829 >>> print("Incorrect decryption")
830
831 CFB mode
832 Cipher FeedBack, defined in NIST SP 800-38A, section 6.3. It is a mode
833 of operation which turns the block cipher into a stream cipher. Each
834 byte of plaintext is XOR-ed with a byte taken from a keystream: the re‐
835 sult is the ciphertext.
836
837 The keystream is obtained on a per-segment basis: the plaintext is bro‐
838 ken up in segments (from 1 byte up to the size of a block). Then, for
839 each segment, the keystream is obtained by encrypting with the block
840 cipher the last piece of ciphertext produced so far - possibly back‐
841 filled with the Initialization Vector, if not enough ciphertext is
842 available yet.
843
844 The new() function at the module level under Crypto.Cipher instantiates
845 a new CFB cipher object for the relevant base algorithm. In the fol‐
846 lowing definition, <algorithm> could be AES:
847
848 Crypto.Cipher.<algorithm>.new(key, mode, *, iv=None, segment_size=8)
849 Create a new CFB object, using <algorithm> as the base block ci‐
850 pher.
851
852 Parameters
853
854 • key (bytes) -- the cryptographic key
855
856 • mode -- the constant Crypto.Cipher.<algorithm>.MODE_CFB
857
858 • iv (bytes) -- the Initialization Vector. It must be
859 unique for the combination message/key. It is as long
860 as the block size (e.g. 16 bytes for AES). If not
861 present, the library creates a random IV.
862
863 • segment_size (integer) -- the number of bits (not
864 bytes!) the plaintext and the ciphertext are segmented
865 in (default if not specified: 8 bits = 1 byte).
866
867 Returns
868 a CFB cipher object
869
870 The methods encrypt() and decrypt() of a CFB cipher object accept data
871 of any length (i.e. padding is not needed).
872
873 The CFB cipher object has a read-only attribute iv (bytes), holding the
874 Initialization Vector.
875
876 Example (encryption):
877
878 >>> import json
879 >>> from base64 import b64encode
880 >>> from Crypto.Cipher import AES
881 >>> from Crypto.Random import get_random_bytes
882 >>>
883 >>> data = b"secret"
884 >>> key = get_random_bytes(16)
885 >>> cipher = AES.new(key, AES.MODE_CFB)
886 >>> ct_bytes = cipher.encrypt(data)
887 >>> iv = b64encode(cipher.iv).decode('utf-8')
888 >>> ct = b64encode(ct_bytes).decode('utf-8')
889 >>> result = json.dumps({'iv':iv, 'ciphertext':ct})
890 >>> print(result)
891 {"iv": "VoamO23kFSOZcK1O2WiCDQ==", "ciphertext": "f8jciJ8/"}
892
893 Example (decryption):
894
895 >>> import json
896 >>> from base64 import b64decode
897 >>> from Crypto.Cipher import AES
898 >>>
899 >>> # We assume that the key was securely shared beforehand
900 >>> try:
901 >>> b64 = json.loads(json_input)
902 >>> iv = b64decode(b64['iv'])
903 >>> ct = b64decode(b64['ciphertext'])
904 >>> cipher = AES.new(key, AES.MODE_CFB, iv=iv)
905 >>> pt = cipher.decrypt(ct)
906 >>> print("The message was: ", pt)
907 >>> except ValueError, KeyError:
908 >>> print("Incorrect decryption")
909
910 OFB mode
911 Output FeedBack, defined in NIST SP 800-38A, section 6.4. It is an‐
912 other mode that leads to a stream cipher. Each byte of plaintext is
913 XOR-ed with a byte taken from a keystream: the result is the cipher‐
914 text. The keystream is obtained by recursively encrypting the Initial‐
915 ization Vector.
916
917 The new() function at the module level under Crypto.Cipher instantiates
918 a new OFB cipher object for the relevant base algorithm. In the fol‐
919 lowing definition, <algorithm> could be AES:
920
921 Crypto.Cipher.<algorithm>.new(key, mode, *, iv=None)
922 Create a new OFB object, using <algorithm> as the base block ci‐
923 pher.
924
925 Parameters
926
927 • key (bytes) -- the cryptographic key
928
929 • mode -- the constant Crypto.Cipher.<algorithm>.MODE_OFB
930
931 • iv (bytes) -- the Initialization Vector. It must be
932 unique for the combination message/key. It is as long
933 as the block size (e.g. 16 bytes for AES). If not
934 present, the library creates a random IV.
935
936 Returns
937 an OFB cipher object
938
939 The methods encrypt() and decrypt() of an OFB cipher object accept data
940 of any length (i.e. padding is not needed).
941
942 The OFB cipher object has a read-only attribute iv (bytes), holding the
943 Initialization Vector.
944
945 Example (encryption):
946
947 >>> import json
948 >>> from base64 import b64encode
949 >>> from Crypto.Cipher import AES
950 >>> from Crypto.Random import get_random_bytes
951 >>>
952 >>> data = b"secret"
953 >>> key = get_random_bytes(16)
954 >>> cipher = AES.new(key, AES.MODE_OFB)
955 >>> ct_bytes = cipher.encrypt(data)
956 >>> iv = b64encode(cipher.iv).decode('utf-8')
957 >>> ct = b64encode(ct_bytes).decode('utf-8')
958 >>> result = json.dumps({'iv':iv, 'ciphertext':ct})
959 >>> print(result)
960 {"iv": "NUuRJbL0UMp8+UMCk2/vQA==", "ciphertext": "XGVGc1Gw"}
961
962 Example (decryption):
963
964 >>> import json
965 >>> from base64 import b64decode
966 >>> from Crypto.Cipher import AES
967 >>>
968 >>> # We assume that the key was securely shared beforehand
969 >>> try:
970 >>> b64 = json.loads(json_input)
971 >>> iv = b64decode(b64['iv'])
972 >>> ct = b64decode(b64['ciphertext'])
973 >>> cipher = AES.new(key, AES.MODE_OFB, iv=iv)
974 >>> pt = cipher.decrypt(ct)
975 >>> print("The message was: ", pt)
976 >>> except ValueError, KeyError:
977 >>> print("Incorrect decryption")
978
979 OpenPGP mode
980 Constant: Crypto.Cipher.<cipher>.MODE_OPENPGP.
981
982 OpenPGP (defined in RFC4880). A variant of CFB, with two differences:
983
984 1. The first invocation to the encrypt() method returns the encrypted
985 IV concatenated to the first chunk of ciphertext (as opposed to the
986 ciphertext only). The encrypted IV is as long as the block size
987 plus 2 more bytes.
988
989 2. When the cipher object is intended for decryption, the parameter iv
990 to new() is the encrypted IV (and not the IV, which is still the
991 case for encryption).
992
993 Like for CTR, an OpenPGP cipher object has a read-only attribute iv.
994
995 Modern modes of operation for symmetric block ciphers
996 Classic modes of operation such as CBC only provide guarantees over the
997 confidentiality of the message but not over its integrity. In other
998 words, they don't allow the receiver to establish if the ciphertext was
999 modified in transit or if it really originates from a certain source.
1000
1001 For that reason, classic modes of operation have been often paired with
1002 a MAC primitive (such as Crypto.Hash.HMAC), but the combination is not
1003 always straightforward, efficient or secure.
1004
1005 Recently, new modes of operations (AEAD, for Authenticated Encryption
1006 with Associated Data) have been designed to combine encryption and au‐
1007 thentication into a single, efficient primitive. Optionally, some part
1008 of the message can also be left in the clear (non-confidential associ‐
1009 ated data, such as headers), while the whole message remains fully au‐
1010 thenticated.
1011
1012 In addition to the ciphertext and a nonce (or IV - Initialization Vec‐
1013 tor), AEAD modes require the additional delivery of a MAC tag.
1014
1015 This is the state machine for a cipher object:
1016 [image] Generic state diagram for a AEAD cipher mode.UNINDENT
1017
1018 Beside the usual encrypt() and decrypt() already available for clas‐
1019 sic modes of operation, several other methods are present:
1020
1021 update(data)
1022 Authenticate those parts of the message that get delivered as
1023 is, without any encryption (like headers). It is similar to the
1024 update() method of a MAC object. Note that all data passed to
1025 encrypt() and decrypt() get automatically authenticated already.
1026
1027 Parameters
1028 data (bytes) -- the extra data to authenticate
1029
1030 digest()
1031 Create the final authentication tag (MAC tag) for a message.
1032
1033 Return bytes
1034 the MAC tag
1035
1036 hexdigest()
1037 Equivalent to digest(), with the output encoded in hexadecimal.
1038
1039 Return str
1040 the MAC tag as a hexadecimal string
1041
1042 verify(mac_tag)
1043 Check if the provided authentication tag (MAC tag) is valid,
1044 that is, if the message has been decrypted using the right key
1045 and if no modification has taken place in transit.
1046
1047 Parameters
1048 mac_tag (bytes) -- the MAC tag
1049
1050 Raises ValueError -- if the MAC tag is not valid, that is, if
1051 the entire message should not be trusted.
1052
1053 hexverify(mac_tag_hex)
1054 Same as verify() but accepts the MAC tag encoded as an hexadeci‐
1055 mal string.
1056
1057 Parameters
1058 mac_tag_hex (str) -- the MAC tag as a hexadecimal string
1059
1060 Raises ValueError -- if the MAC tag is not valid, that is, if
1061 the entire message should not be trusted.
1062
1063 encrypt_and_digest(plaintext, output=None)
1064 Perform encrypt() and digest() in one go.
1065
1066 Parameters
1067 plaintext (bytes) -- the last piece of plaintext to en‐
1068 crypt
1069
1070 Keyword Arguments
1071 output (bytes/bytearray/memoryview) -- the pre-allocated
1072 buffer where the ciphertext must be stored (as opposed to
1073 being returned).
1074
1075 Returns
1076 a tuple with two items
1077
1078 • the ciphertext, as bytes
1079
1080 • the MAC tag, as bytes
1081
1082 The first item becomes None when the output parameter
1083 specified a location for the result.
1084
1085
1086 decrypt_and_verify(ciphertext, mac_tag, output=None)
1087 Perform decrypt() and verify() in one go.
1088
1089 Parameters
1090 ciphertext (bytes) -- the last piece of ciphertext to de‐
1091 crypt
1092
1093 Keyword Arguments
1094 output (bytes/bytearray/memoryview) -- the pre-allocated
1095 buffer where the plaintext must be stored (as opposed to
1096 being returned).
1097
1098 Raises ValueError -- if the MAC tag is not valid, that is, if
1099 the entire message should not be trusted.
1100
1101 CCM mode
1102 Counter with CBC-MAC, defined in RFC3610 or NIST SP 800-38C. It only
1103 works with ciphers having block size 128 bits (like AES).
1104
1105 The new() function at the module level under Crypto.Cipher instantiates
1106 a new CCM cipher object for the relevant base algorithm. In the fol‐
1107 lowing definition, <algorithm> can only be AES today:
1108
1109 Crypto.Cipher.<algorithm>.new(key, mode, *, nonce=None, mac_len=None,
1110 msg_len=None, assoc_len=None)
1111 Create a new CCM object, using <algorithm> as the base block ci‐
1112 pher.
1113
1114 Parameters
1115
1116 • key (bytes) -- the cryptographic key
1117
1118 • mode -- the constant Crypto.Cipher.<algorithm>.MODE_CCM
1119
1120 • nonce (bytes) -- the value of the fixed nonce. It must
1121 be unique for the combination message/key. For AES,
1122 its length varies from 7 to 13 bytes. The longer the
1123 nonce, the smaller the allowed message size (with a
1124 nonce of 13 bytes, the message cannot exceed 64KB). If
1125 not present, the library creates a 11 bytes random
1126 nonce (the maximum message size is 8GB).
1127
1128 • mac_len (integer) -- the desired length of the MAC tag
1129 (default if not present: 16 bytes).
1130
1131 • msg_len (integer) -- pre-declaration of the length of
1132 the message to encipher. If not specified, encrypt()
1133 and decrypt() can only be called once.
1134
1135 • assoc_len (integer) -- pre-declaration of the length of
1136 the associated data. If not specified, some extra
1137 buffering will take place internally.
1138
1139 Returns
1140 a CTR cipher object
1141
1142 The cipher object has a read-only attribute nonce.
1143
1144 Example (encryption):
1145
1146 >>> import json
1147 >>> from base64 import b64encode
1148 >>> from Crypto.Cipher import AES
1149 >>> from Crypto.Random import get_random_bytes
1150 >>>
1151 >>> header = b"header"
1152 >>> data = b"secret"
1153 >>> key = get_random_bytes(16)
1154 >>> cipher = AES.new(key, AES.MODE_CCM)
1155 >>> cipher.update(header)
1156 >>> ciphertext, tag = cipher.encrypt_and_digest(data)
1157 >>>
1158 >>> json_k = [ 'nonce', 'header', 'ciphertext', 'tag' ]
1159 >>> json_v = [ b64encode(x).decode('utf-8') for x in cipher.nonce, header, ciphertext, tag ]
1160 >>> result = json.dumps(dict(zip(json_k, json_v)))
1161 >>> print(result)
1162 {"nonce": "p6ffzcKw+6xopVQ=", "header": "aGVhZGVy", "ciphertext": "860kZo/G", "tag": "Ck5YpVCM6fdWnFkFxw8K6A=="}
1163
1164 Example (decryption):
1165
1166 >>> import json
1167 >>> from base64 import b64decode
1168 >>> from Crypto.Cipher import AES
1169 >>>
1170 >>> # We assume that the key was securely shared beforehand
1171 >>> try:
1172 >>> b64 = json.loads(json_input)
1173 >>> json_k = [ 'nonce', 'header', 'ciphertext', 'tag' ]
1174 >>> jv = {k:b64decode(b64[k]) for k in json_k}
1175 >>>
1176 >>> cipher = AES.new(key, AES.MODE_CCM, nonce=jv['nonce'])
1177 >>> cipher.update(jv['header'])
1178 >>> plaintext = cipher.decrypt_and_verify(jv['ciphertext'], jv['tag'])
1179 >>> print("The message was: " + plaintext)
1180 >>> except ValueError, KeyError:
1181 >>> print("Incorrect decryption")
1182
1183 EAX mode
1184 An AEAD mode designed for NIST by Bellare, Rogaway, and Wagner in 2003.
1185
1186 The new() function at the module level under Crypto.Cipher instantiates
1187 a new EAX cipher object for the relevant base algorithm.
1188
1189 Crypto.Cipher.<algorithm>.new(key, mode, *, nonce=None, mac_len=None)
1190 Create a new EAX object, using <algorithm> as the base block ci‐
1191 pher.
1192
1193 Parameters
1194
1195 • key (bytes) -- the cryptographic key
1196
1197 • mode -- the constant Crypto.Cipher.<algorithm>.MODE_EAX
1198
1199 • nonce (bytes) -- the value of the fixed nonce. It must
1200 be unique for the combination message/key. If not
1201 present, the library creates a random nonce (16 bytes
1202 long for AES).
1203
1204 • mac_len (integer) -- the desired length of the MAC tag
1205 (default if not present: the cipher's block size, 16
1206 bytes for AES).
1207
1208 Returns
1209 an EAX cipher object
1210
1211 The cipher object has a read-only attribute nonce.
1212
1213 Example (encryption):
1214
1215 >>> import json
1216 >>> from base64 import b64encode
1217 >>> from Crypto.Cipher import AES
1218 >>> from Crypto.Random import get_random_bytes
1219 >>>
1220 >>> header = b"header"
1221 >>> data = b"secret"
1222 >>> key = get_random_bytes(16)
1223 >>> cipher = AES.new(key, AES.MODE_EAX)
1224 >>> cipher.update(header)
1225 >>> ciphertext, tag = cipher.encrypt_and_digest(data)
1226 >>>
1227 >>> json_k = [ 'nonce', 'header', 'ciphertext', 'tag' ]
1228 >>> json_v = [ b64encode(x).decode('utf-8') for x in cipher.nonce, header, ciphertext, tag ]
1229 >>> result = json.dumps(dict(zip(json_k, json_v)))
1230 >>> print(result)
1231 {"nonce": "CSIJ+e8KP7HJo+hC4RXIyQ==", "header": "aGVhZGVy", "ciphertext": "9YYjuAn6", "tag": "kXHrs9ZwYmjDkmfEJx7Clg=="}
1232
1233 Example (decryption):
1234
1235 >>> import json
1236 >>> from base64 import b64decode
1237 >>> from Crypto.Cipher import AES
1238 >>>
1239 >>> # We assume that the key was securely shared beforehand
1240 >>> try:
1241 >>> b64 = json.loads(json_input)
1242 >>> json_k = [ 'nonce', 'header', 'ciphertext', 'tag' ]
1243 >>> jv = {k:b64decode(b64[k]) for k in json_k}
1244 >>>
1245 >>> cipher = AES.new(key, AES.MODE_EAX, nonce=jv['nonce'])
1246 >>> cipher.update(jv['header'])
1247 >>> plaintext = cipher.decrypt_and_verify(jv['ciphertext'], jv['tag'])
1248 >>> print("The message was: " + plaintext)
1249 >>> except ValueError, KeyError:
1250 >>> print("Incorrect decryption")
1251
1252 GCM mode
1253 Galois/Counter Mode, defined in NIST SP 800-38D. It only works in com‐
1254 bination with a 128 bits cipher like AES.
1255
1256 The new() function at the module level under Crypto.Cipher instantiates
1257 a new GCM cipher object for the relevant base algorithm.
1258
1259 Crypto.Cipher.<algorithm>.new(key, mode, *, nonce=None, mac_len=None)
1260 Create a new GCM object, using <algorithm> as the base block ci‐
1261 pher.
1262
1263 Parameters
1264
1265 • key (bytes) -- the cryptographic key
1266
1267 • mode -- the constant Crypto.Cipher.<algorithm>.MODE_GCM
1268
1269 • nonce (bytes) -- the value of the fixed nonce. It must
1270 be unique for the combination message/key. If not
1271 present, the library creates a random nonce (16 bytes
1272 long for AES).
1273
1274 • mac_len (integer) -- the desired length of the MAC tag,
1275 from 4 to 16 bytes (default: 16).
1276
1277 Returns
1278 a GCM cipher object
1279
1280 The cipher object has a read-only attribute nonce.
1281
1282 Example (encryption):
1283
1284 >>> import json
1285 >>> from base64 import b64encode
1286 >>> from Crypto.Cipher import AES
1287 >>> from Crypto.Random import get_random_bytes
1288 >>>
1289 >>> header = b"header"
1290 >>> data = b"secret"
1291 >>> key = get_random_bytes(16)
1292 >>> cipher = AES.new(key, AES.MODE_GCM)
1293 >>> cipher.update(header)
1294 >>> ciphertext, tag = cipher.encrypt_and_digest(data)
1295 >>>
1296 >>> json_k = [ 'nonce', 'header', 'ciphertext', 'tag' ]
1297 >>> json_v = [ b64encode(x).decode('utf-8') for x in [cipher.nonce, header, ciphertext, tag ]]
1298 >>> result = json.dumps(dict(zip(json_k, json_v)))
1299 >>> print(result)
1300 {"nonce": "DpOK8NIOuSOQlTq+BphKWw==", "header": "aGVhZGVy", "ciphertext": "CZVqyacc", "tag": "B2tBgICbyw+Wji9KpLVa8w=="}
1301
1302 Example (decryption):
1303
1304 >>> import json
1305 >>> from base64 import b64decode
1306 >>> from Crypto.Cipher import AES
1307 >>> from Crypto.Util.Padding import unpad
1308 >>>
1309 >>> # We assume that the key was securely shared beforehand
1310 >>> try:
1311 >>> b64 = json.loads(json_input)
1312 >>> json_k = [ 'nonce', 'header', 'ciphertext', 'tag' ]
1313 >>> jv = {k:b64decode(b64[k]) for k in json_k}
1314 >>>
1315 >>> cipher = AES.new(key, AES.MODE_GCM, nonce=jv['nonce'])
1316 >>> cipher.update(jv['header'])
1317 >>> plaintext = cipher.decrypt_and_verify(jv['ciphertext'], jv['tag'])
1318 >>> print("The message was: " + plaintext)
1319 >>> except ValueError, KeyError:
1320 >>> print("Incorrect decryption")
1321
1322 NOTE:
1323 GCM is most commonly used with 96-bit (12-byte) nonces, which is
1324 also the length recommended by NIST SP 800-38D.
1325
1326 If interoperability is important, one should take into account that
1327 the library default of a 128-bit random nonce may not be (easily)
1328 supported by other implementations. A 96-bit nonce can be explic‐
1329 itly generated for a new encryption cipher:
1330
1331 >>> key = get_random_bytes(16)
1332 >>> nonce = get_random_bytes(12)
1333 >>> cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
1334
1335 SIV mode
1336 Synthetic Initialization Vector (SIV), defined in RFC5297. It only
1337 works with ciphers with a block size of 128 bits (like AES).
1338
1339 Although less efficient than other modes, SIV is nonce misuse-resis‐
1340 tant: accidental reuse of the nonce does not jeopardize the security as
1341 it happens with CCM or GCM. As a matter of fact, operating without a
1342 nonce is not an error per se: the cipher simply becomes deterministic.
1343 In other words, a message gets always encrypted into the same cipher‐
1344 text.
1345
1346 The new() function at the module level under Crypto.Cipher instantiates
1347 a new SIV cipher object for the relevant base algorithm.
1348
1349 Crypto.Cipher.<algorithm>.new(key, mode, *, nonce=None)
1350 Create a new SIV object, using <algorithm> as the base block ci‐
1351 pher.
1352
1353 Parameters
1354
1355 • key (bytes) -- the cryptographic key; it must be twice
1356 the size of the key required by the underlying cipher
1357 (e.g. 32 bytes for AES-128).
1358
1359 • mode -- the constant Crypto.Cipher.<algorithm>.MODE_SIV
1360
1361 • nonce (bytes) -- the value of the fixed nonce. It must
1362 be unique for the combination message/key. If not
1363 present, the encryption will be deterministic.
1364
1365 Returns
1366 a SIV cipher object
1367
1368 If the nonce parameter was provided to new(), the resulting cipher ob‐
1369 ject has a read-only attribute nonce.
1370
1371 Example (encryption):
1372
1373 >>> import json
1374 >>> from base64 import b64encode
1375 >>> from Crypto.Cipher import AES
1376 >>> from Crypto.Random import get_random_bytes
1377 >>>
1378 >>> header = b"header"
1379 >>> data = b"secret"
1380 >>> key = get_random_bytes(16 * 2)
1381 >>> nonce = get_random_bytes(16)
1382 >>> cipher = AES.new(key, AES.MODE_SIV, nonce=nonce) # Without nonce, the encryption
1383 >>> # becomes deterministic
1384 >>> cipher.update(header)
1385 >>> ciphertext, tag = cipher.encrypt_and_digest(data)
1386 >>>
1387 >>> json_k = [ 'nonce', 'header', 'ciphertext', 'tag' ]
1388 >>> json_v = [ b64encode(x).decode('utf-8') for x in nonce, header, ciphertext, tag ]
1389 >>> result = json.dumps(dict(zip(json_k, json_v)))
1390 >>> print(result)
1391 {"nonce": "zMiifAVvDpMS8hnGK/z+iw==", "header": "aGVhZGVy", "ciphertext": "Q7lReEAF", "tag": "KgdnBVbCee6B/wGmMf/wQA=="}
1392
1393 Example (decryption):
1394
1395 >>> import json
1396 >>> from base64 import b64decode
1397 >>> from Crypto.Cipher import AES
1398 >>>
1399 >>> # We assume that the key was securely shared beforehand
1400 >>> try:
1401 >>> b64 = json.loads(json_input)
1402 >>> json_k = [ 'nonce', 'header', 'ciphertext', 'tag' ]
1403 >>> jv = {k:b64decode(b64[k]) for k in json_k}
1404 >>>
1405 >>> cipher = AES.new(key, AES.MODE_SIV, nonce=jv['nonce'])
1406 >>> cipher.update(jv['header'])
1407 >>> plaintext = cipher.decrypt_and_verify(jv['ciphertext'], jv['tag'])
1408 >>> print("The message was: " + plaintext)
1409 >>> except ValueError, KeyError:
1410 >>> print("Incorrect decryption")
1411
1412 One side-effect is that encryption (or decryption) must take place in
1413 one go with the method encrypt_and_digest() (or decrypt_and_verify()).
1414 You cannot use encrypt() or decrypt(). The state diagram is therefore:
1415 [image] State diagram for the SIV cipher mode.UNINDENT
1416
1417 The length of the key passed to new() must be twice as required by
1418 the underlying block cipher (e.g. 32 bytes for AES-128).
1419
1420 Each call to the method update() consumes an full piece of associated
1421 data. That is, the sequence:
1422
1423 >>> siv_cipher.update(b"builtin")
1424 >>> siv_cipher.update(b"securely")
1425
1426 is not equivalent to:
1427
1428 >>> siv_cipher.update(b"built")
1429 >>> siv_cipher.update(b"insecurely")
1430
1431 OCB mode
1432 Offset CodeBook mode, a cipher designed by Rogaway and specified in
1433 RFC7253 (more specifically, this module implements the last variant,
1434 OCB3). It only works in combination with a 128 bits cipher like AES.
1435
1436 OCB is patented in USA but free licenses exist for software implementa‐
1437 tions meant for non-military purposes and open source.
1438
1439 The new() function at the module level under Crypto.Cipher instantiates
1440 a new OCB cipher object for the relevant base algorithm.
1441
1442 Crypto.Cipher.<algorithm>.new(key, mode, *, nonce=None, mac_len=None)
1443 Create a new OCB object, using <algorithm> as the base block ci‐
1444 pher.
1445
1446 Parameters
1447
1448 • key (bytes) -- the cryptographic key
1449
1450 • mode -- the constant Crypto.Cipher.<algorithm>.MODE_OCB
1451
1452 • nonce (bytes) -- the value of the fixed nonce, wuth
1453 length between 1 and 15 bytes. It must be unique for
1454 the combination message/key. If not present, the li‐
1455 brary creates a 15 bytes random nonce.
1456
1457 • mac_len (integer) -- the desired length of the MAC tag
1458 (default if not present: 16 bytes).
1459
1460 Returns
1461 an OCB cipher object
1462
1463 The cipher object has a read-only attribute nonce.
1464
1465 Example (encryption):
1466
1467 >>> import json
1468 >>> from base64 import b64encode
1469 >>> from Crypto.Cipher import AES
1470 >>> from Crypto.Random import get_random_bytes
1471 >>>
1472 >>> header = b"header"
1473 >>> data = b"secret"
1474 >>> key = get_random_bytes(16)
1475 >>> cipher = AES.new(key, AES.MODE_OCB)
1476 >>> cipher.update(header)
1477 >>> ciphertext, tag = cipher.encrypt_and_digest(data)
1478 >>>
1479 >>> json_k = [ 'nonce', 'header', 'ciphertext', 'tag' ]
1480 >>> json_v = [ b64encode(x).decode('utf-8') for x in cipher.nonce, header, ciphertext, tag ]
1481 >>> result = json.dumps(dict(zip(json_k, json_v)))
1482 >>> print(result)
1483 {"nonce": "I7E6PKxHNYo2i9sz8W98", "header": "aGVhZGVy", "ciphertext": "nYJnJ8jC", "tag": "0UbFcmO9lqGknCIDWRLALA=="}
1484
1485 Example (decryption):
1486
1487 >>> import json
1488 >>> from base64 import b64decode
1489 >>> from Crypto.Cipher import AES
1490 >>>
1491 >>> # We assume that the key was securely shared beforehand
1492 >>> try:
1493 >>> b64 = json.loads(json_input)
1494 >>> json_k = [ 'nonce', 'header', 'ciphertext', 'tag' ]
1495 >>> jv = {k:b64decode(b64[k]) for k in json_k}
1496 >>>
1497 >>> cipher = AES.new(key, AES.MODE_OCB, nonce=jv['nonce'])
1498 >>> cipher.update(jv['header'])
1499 >>> plaintext = cipher.decrypt_and_verify(jv['ciphertext'], jv['tag'])
1500 >>> print("The message was: " + plaintext)
1501 >>> except ValueError, KeyError:
1502 >>> print("Incorrect decryption")
1503
1504 Legacy ciphers
1505 A number of ciphers are implemented in this library purely for backward
1506 compatibility purposes. They are deprecated or even fully broken and
1507 should not be used in new designs.
1508
1509 • des and des3 (block ciphers)
1510
1511 • arc2 (block cipher)
1512
1513 • arc4 (stream cipher)
1514
1515 • blowfish (block cipher)
1516
1517 • cast (block cipher)
1518
1519 • pkcs1_v1_5 (asymmetric cipher)
1520
1521 Crypto.Signature package
1522 The Crypto.Signature package contains algorithms for performing digital
1523 signatures, used to guarantee integrity and non-repudiation.
1524
1525 Digital signatures are based on public key cryptography: the party that
1526 signs a message holds the private key, the one that verifies the signa‐
1527 ture holds the public key.
1528
1529 Signing a message
1530 1. Instantiate a new signer object for the desired algorithm, for in‐
1531 stance with Crypto.Signature.pkcs1_15.new(). The first parameter is
1532 the key object (private key) obtained via the Crypto.PublicKey mod‐
1533 ule.
1534
1535 2. Instantiate a cryptographic hash object, for instance with
1536 Crypto.Hash.SHA384.new(). Then, process the message with its up‐
1537 date() method.
1538
1539 3. Invoke the sign() method on the signer with the hash object as pa‐
1540 rameter. The output is the signature of the message (a byte
1541 string).
1542
1543 Verifying a signature
1544 1. Instantiate a new verifier object for the desired algorithm, for in‐
1545 stance with Crypto.Signature.pkcs1_15.new(). The first parameter is
1546 the key object (public key) obtained via the Crypto.PublicKey mod‐
1547 ule.
1548
1549 2. Instantiate a cryptographic hash object, for instance with
1550 Crypto.Hash.SHA384.new(). Then, process the message with its up‐
1551 date() method.
1552
1553 3. Invoke the verify() method on the verifier, with the hash object and
1554 the incoming signature as parameters. If the message is not authen‐
1555 tic, an ValueError is raised.
1556
1557 Available mechanisms
1558 • pkcs1_v1_5
1559
1560 • pkcs1_pss
1561
1562 • dsa
1563
1564 Crypto.Hash package
1565 Cryptographic hash functions take arbitrary binary strings as input,
1566 and produce a random-like fixed-length output (called digest or hash
1567 value).
1568
1569 It is practically infeasible to derive the original input data from the
1570 digest. In other words, the cryptographic hash function is one-way
1571 (pre-image resistance).
1572
1573 Given the digest of one message, it is also practically infeasible to
1574 find another message (second pre-image) with the same digest (weak col‐
1575 lision resistance).
1576
1577 Finally, it is infeasible to find two arbitrary messages with the same
1578 digest (strong collision resistance).
1579
1580 Regardless of the hash algorithm, an n bits long digest is at most as
1581 secure as a symmetric encryption algorithm keyed with n/2 bits (‐
1582 birthday attack).
1583
1584 Hash functions can be simply used as integrity checks. In combination
1585 with a public-key algorithm, you can implement a digital signature.
1586
1587 API principles
1588 [image] Generic state diagram for a hash object.UNINDENT
1589
1590 Every time you want to hash a message, you have to create a new hash
1591 object with the new() function in the relevant algorithm module (e.g.
1592 Crypto.Hash.SHA256.new()).
1593
1594 A first piece of message to hash can be passed to new() with the data
1595 parameter:
1596
1597 >> from Crypto.Hash import SHA256
1598 >>
1599 >> hash_object = SHA256.new(data=b'First')
1600
1601 NOTE:
1602 You can only hash byte strings or byte arrays (no Python 2 Unicode
1603 strings or Python 3 strings).
1604
1605 Afterwards, the method update() can be invoked any number of times as
1606 necessary, with other pieces of message:
1607
1608 >>> hash_object.update(b'Second')
1609 >>> hash_object.update(b'Third')
1610
1611 The two steps above are equivalent to:
1612
1613 >>> hash_object.update(b'SecondThird')
1614
1615 At the end, the digest can be retrieved with the methods digest() or
1616 hexdigest():
1617
1618 >>> print(hash_object.digest())
1619 b'}\x96\xfd@\xb2$?O\xca\xc1a\x10\x15\x8c\x94\xe4\xb4\x085"\xd5"\xa8\xa4C\x9e+\x00\x859\xc7A'
1620 >>> print(hash_object.hexdigest())
1621 7d96fd40b2243f4fcac16110158c94e4b4083522d522a8a4439e2b008539c741
1622
1623 Attributes of hash objects
1624 Every hash object has the following attributes:
1625
1626 ┌────────────┬────────────────────────────┐
1627 │Attribute │ Description │
1628 ├────────────┼────────────────────────────┤
1629 │digest_size │ Size of the digest in │
1630 │ │ bytes, that is, the output │
1631 │ │ of the digest() method. │
1632 │ │ It does not exist for hash │
1633 │ │ functions with variable │
1634 │ │ digest output (such as │
1635 │ │ Crypto.Hash.SHAKE128). │
1636 │ │ This is also a module at‐ │
1637 │ │ tribute. │
1638 ├────────────┼────────────────────────────┤
1639 │block_size │ The size of the message │
1640 │ │ block in bytes, input to │
1641 │ │ the compression function. │
1642 │ │ Only applicable for algo‐ │
1643 │ │ rithms based on the │
1644 │ │ Merkle-Damgard construc‐ │
1645 │ │ tion (e.g. │
1646 │ │ Crypto.Hash.SHA256). This │
1647 │ │ is also a module attri‐ │
1648 │ │ bute. │
1649 ├────────────┼────────────────────────────┤
1650 │oid │ A string with the dotted │
1651 │ │ representation of the │
1652 │ │ ASN.1 OID assigned to the │
1653 │ │ hash algorithm. │
1654 └────────────┴────────────────────────────┘
1655
1656 Modern hash algorithms
1657 • SHA-2 family
1658
1659 • sha224
1660
1661 • sha256
1662
1663 • sha384
1664
1665 • sha512
1666
1667 • SHA-3 family
1668
1669 • sha3_224
1670
1671 • sha3_256
1672
1673 • sha3_384
1674
1675 • sha3_512
1676
1677 • BLAKE2
1678
1679 • blake2s
1680
1681 • blake2b
1682
1683 Extensible-Output Functions (XOF)
1684 • SHAKE and cSHAKE (in the SHA-3 family)
1685
1686 • shake128
1687
1688 • shake256
1689
1690 • cshake128
1691
1692 • cshake256
1693
1694 Message Authentication Code (MAC) algorithms
1695 • hmac
1696
1697 • cmac
1698
1699 • poly1305
1700
1701 Historic hash algorithms
1702 The following algorithms should not be used in new designs:
1703
1704 • sha1
1705
1706 • md2
1707
1708 • md5
1709
1710 • ripemd160
1711
1712 • keccak
1713
1714 Crypto.PublicKey package
1715 In a public key cryptography system, senders and receivers do not use
1716 the same key. Instead, the system defines a key pair, with one of the
1717 keys being confidential (private) and the other not (public).
1718
1719 ┌───────────┬───────────────┬──────────────────┐
1720 │Algorithm │ Sender uses.. │ Receiver uses... │
1721 ├───────────┼───────────────┼──────────────────┤
1722 │Encryption │ Public key │ Private key │
1723 ├───────────┼───────────────┼──────────────────┤
1724 │Signature │ Private key │ Public key │
1725 └───────────┴───────────────┴──────────────────┘
1726
1727 Unlike keys meant for symmetric cipher algorithms (typically just ran‐
1728 dom bit strings), keys for public key algorithms have very specific
1729 properties. This module collects all methods to generate, validate,
1730 store and retrieve public keys.
1731
1732 API principles
1733 Asymmetric keys are represented by Python objects. Each object can be
1734 either a private key or a public key (the method has_private() can be
1735 used to distinguish them).
1736
1737 A key object can be created in four ways:
1738
1739 1. generate() at the module level (e.g. Crypto.PublicKey.RSA.gener‐
1740 ate()). The key is randomly created each time.
1741
1742 2. import_key() at the module level (e.g. Crypto.PublicKey.RSA.im‐
1743 port_key()). The key is loaded from memory.
1744
1745 3. construct() at the module level (e.g. Crypto.PublicKey.RSA.con‐
1746 struct()). The key will be built from a set of sub-components.
1747
1748 4. publickey() at the object level (e.g. Crypto.Pub‐
1749 licKey.RSA.RsaKey.publickey()). The key will be the public key
1750 matching the given object.
1751
1752 A key object can be serialized via its export_key() method.
1753
1754 Keys objects can be compared via the usual operators == and != (note
1755 that the two halves of the same key, private and public, are considered
1756 as two different keys).
1757
1758 Available key types
1759 RSA
1760 RSA is the most widespread and used public key algorithm. Its security
1761 is based on the difficulty of factoring large integers. The algorithm
1762 has withstood attacks for more than 30 years, and it is therefore con‐
1763 sidered reasonably secure for new designs.
1764
1765 The algorithm can be used for both confidentiality (encryption) and au‐
1766 thentication (digital signature). It is worth noting that signing and
1767 decryption are significantly slower than verification and encryption.
1768
1769 The cryptographic strength is primarily linked to the length of the RSA
1770 modulus n. In 2017, a sufficient length is deemed to be 2048 bits. For
1771 more information, see the most recent ECRYPT report.
1772
1773 Both RSA ciphertexts and RSA signatures are as large as the RSA modulus
1774 n (256 bytes if n is 2048 bit long).
1775
1776 The module Crypto.PublicKey.RSA provides facilities for generating new
1777 RSA keys, reconstructing them from known components, exporting them,
1778 and importing them.
1779
1780 As an example, this is how you generate a new RSA key pair, save it in
1781 a file called mykey.pem, and then read it back:
1782
1783 >>> from Crypto.PublicKey import RSA
1784 >>>
1785 >>> key = RSA.generate(2048)
1786 >>> f = open('mykey.pem','wb')
1787 >>> f.write(key.export_key('PEM'))
1788 >>> f.close()
1789 ...
1790 >>> f = open('mykey.pem','r')
1791 >>> key = RSA.import_key(f.read())
1792
1793 class Crypto.PublicKey.RSA.RsaKey(**kwargs)
1794 Class defining an actual RSA key. Do not instantiate directly.
1795 Use generate(), construct() or import_key() instead.
1796
1797 Variables
1798
1799 • n (integer) -- RSA modulus
1800
1801 • e (integer) -- RSA public exponent
1802
1803 • d (integer) -- RSA private exponent
1804
1805 • p (integer) -- First factor of the RSA modulus
1806
1807 • q (integer) -- Second factor of the RSA modulus
1808
1809 • u (integer) -- Chinese remainder component (p^{-1}
1810 \text{mod } q)
1811
1812 Undocumented
1813 exportKey, publickey
1814
1815 exportKey(format='PEM', passphrase=None, pkcs=1, protec‐
1816 tion=None, randfunc=None)
1817 Export this RSA key.
1818
1819 Parameters
1820
1821 • format (string) --
1822
1823 The format to use for wrapping the key:
1824
1825 • 'PEM'. (Default) Text encoding, done according
1826 to RFC1421/RFC1423.
1827
1828 • 'DER'. Binary encoding.
1829
1830 • 'OpenSSH'. Textual encoding, done according to
1831 OpenSSH specification. Only suitable for pub‐
1832 lic keys (not private keys).
1833
1834
1835 • passphrase (string) -- (For private keys only)
1836 The pass phrase used for protecting the output.
1837
1838 • pkcs (integer) --
1839
1840 (For private keys only) The ASN.1 structure to
1841 use for serializing the key. Note that even in
1842 case of PEM encoding, there is an inner ASN.1
1843 DER structure.
1844
1845 With pkcs=1 (default), the private key is en‐
1846 coded in a simple PKCS#1 structure (RSAPri‐
1847 vateKey).
1848
1849 With pkcs=8, the private key is encoded in a
1850 PKCS#8 structure (PrivateKeyInfo).
1851
1852 NOTE:
1853 This parameter is ignored for a public key.
1854 For DER and PEM, an ASN.1 DER SubjectPublicK‐
1855 eyInfo structure is always used.
1856
1857
1858 • protection (string) --
1859
1860 (For private keys only) The encryption scheme to
1861 use for protecting the private key.
1862
1863 If None (default), the behavior depends on for‐
1864 mat:
1865
1866 • For 'DER', the PBKDF2WithHMAC-SHA1And‐
1867 DES-EDE3-CBC scheme is used. The following op‐
1868 erations are performed:
1869
1870 1. A 16 byte Triple DES key is derived from
1871 the passphrase using Crypto.Proto‐
1872 col.KDF.PBKDF2() with 8 bytes salt, and
1873 1 000 iterations of Crypto.Hash.HMAC.
1874
1875 2. The private key is encrypted using CBC.
1876
1877 3. The encrypted key is encoded according
1878 to PKCS#8.
1879
1880 • For 'PEM', the obsolete PEM encryption scheme
1881 is used. It is based on MD5 for key deriva‐
1882 tion, and Triple DES for encryption.
1883
1884 Specifying a value for protection is only mean‐
1885 ingful for PKCS#8 (that is, pkcs=8) and only if
1886 a pass phrase is present too.
1887
1888 The supported schemes for PKCS#8 are listed in
1889 the Crypto.IO.PKCS8 module (see wrap_algo param‐
1890 eter).
1891
1892
1893 • randfunc (callable) -- A function that provides
1894 random bytes. Only used for PEM encoding. The
1895 default is Crypto.Random.get_random_bytes().
1896
1897 Returns
1898 the encoded key
1899
1900 Return type
1901 byte string
1902
1903 Raises ValueError -- when the format is unknown or when
1904 you try to encrypt a private
1905 key with DER format and PKCS#1.
1906
1907 WARNING:
1908 If you don't provide a pass phrase, the private key
1909 will be exported in the clear!
1910
1911 export_key(format='PEM', passphrase=None, pkcs=1, protec‐
1912 tion=None, randfunc=None)
1913 Export this RSA key.
1914
1915 Parameters
1916
1917 • format (string) --
1918
1919 The format to use for wrapping the key:
1920
1921 • 'PEM'. (Default) Text encoding, done according
1922 to RFC1421/RFC1423.
1923
1924 • 'DER'. Binary encoding.
1925
1926 • 'OpenSSH'. Textual encoding, done according to
1927 OpenSSH specification. Only suitable for pub‐
1928 lic keys (not private keys).
1929
1930
1931 • passphrase (string) -- (For private keys only)
1932 The pass phrase used for protecting the output.
1933
1934 • pkcs (integer) --
1935
1936 (For private keys only) The ASN.1 structure to
1937 use for serializing the key. Note that even in
1938 case of PEM encoding, there is an inner ASN.1
1939 DER structure.
1940
1941 With pkcs=1 (default), the private key is en‐
1942 coded in a simple PKCS#1 structure (RSAPri‐
1943 vateKey).
1944
1945 With pkcs=8, the private key is encoded in a
1946 PKCS#8 structure (PrivateKeyInfo).
1947
1948 NOTE:
1949 This parameter is ignored for a public key.
1950 For DER and PEM, an ASN.1 DER SubjectPublicK‐
1951 eyInfo structure is always used.
1952
1953
1954 • protection (string) --
1955
1956 (For private keys only) The encryption scheme to
1957 use for protecting the private key.
1958
1959 If None (default), the behavior depends on for‐
1960 mat:
1961
1962 • For 'DER', the PBKDF2WithHMAC-SHA1And‐
1963 DES-EDE3-CBC scheme is used. The following op‐
1964 erations are performed:
1965
1966 1. A 16 byte Triple DES key is derived from
1967 the passphrase using Crypto.Proto‐
1968 col.KDF.PBKDF2() with 8 bytes salt, and
1969 1 000 iterations of Crypto.Hash.HMAC.
1970
1971 2. The private key is encrypted using CBC.
1972
1973 3. The encrypted key is encoded according
1974 to PKCS#8.
1975
1976 • For 'PEM', the obsolete PEM encryption scheme
1977 is used. It is based on MD5 for key deriva‐
1978 tion, and Triple DES for encryption.
1979
1980 Specifying a value for protection is only mean‐
1981 ingful for PKCS#8 (that is, pkcs=8) and only if
1982 a pass phrase is present too.
1983
1984 The supported schemes for PKCS#8 are listed in
1985 the Crypto.IO.PKCS8 module (see wrap_algo param‐
1986 eter).
1987
1988
1989 • randfunc (callable) -- A function that provides
1990 random bytes. Only used for PEM encoding. The
1991 default is Crypto.Random.get_random_bytes().
1992
1993 Returns
1994 the encoded key
1995
1996 Return type
1997 byte string
1998
1999 Raises ValueError -- when the format is unknown or when
2000 you try to encrypt a private
2001 key with DER format and PKCS#1.
2002
2003 WARNING:
2004 If you don't provide a pass phrase, the private key
2005 will be exported in the clear!
2006
2007 has_private()
2008 Whether this is an RSA private key
2009
2010 public_key()
2011 A matching RSA public key.
2012
2013 Returns
2014 a new RsaKey object
2015
2016 publickey()
2017 A matching RSA public key.
2018
2019 Returns
2020 a new RsaKey object
2021
2022 size_in_bits()
2023 Size of the RSA modulus in bits
2024
2025 size_in_bytes()
2026 The minimal amount of bytes that can hold the RSA modulus
2027
2028 Crypto.PublicKey.RSA.construct(rsa_components, consistency_check=True)
2029 Construct an RSA key from a tuple of valid RSA components.
2030
2031 The modulus n must be the product of two primes. The public ex‐
2032 ponent e must be odd and larger than 1.
2033
2034 In case of a private key, the following equations must apply:
2035
2036 \begin{align}
2037 p*q &= n \\ e*d &\equiv 1 ( \text{mod lcm} [(p-1)(q-1)]) \\ p*u
2038 &\equiv 1 ( \text{mod } q) \end{align}
2039
2040 Parameters
2041
2042 • rsa_components (tuple) --
2043
2044 A tuple of integers, with at least 2 and no more than 6
2045 items. The items come in the following order:
2046
2047 1. RSA modulus n.
2048
2049 2. Public exponent e.
2050
2051 3. Private exponent d. Only required if the key is
2052 private.
2053
2054 4. First factor of n (p). Optional, but the other fac‐
2055 tor q must also be present.
2056
2057 5. Second factor of n (q). Optional.
2058
2059 6. CRT coefficient q, that is p^{-1} \text{mod }q. Op‐
2060 tional.
2061
2062
2063 • consistency_check (boolean) -- If True, the library
2064 will verify that the provided components fulfil the
2065 main RSA properties.
2066
2067 Raises ValueError -- when the key being imported fails the most
2068 basic RSA validity checks.
2069
2070 Returns: An RSA key object (RsaKey).
2071
2072 Crypto.PublicKey.RSA.generate(bits, randfunc=None, e=65537)
2073 Create a new RSA key pair.
2074
2075 The algorithm closely follows NIST FIPS 186-4 in its sections
2076 B.3.1 and B.3.3. The modulus is the product of two non-strong
2077 probable primes. Each prime passes a suitable number of
2078 Miller-Rabin tests with random bases and a single Lucas test.
2079
2080 Parameters
2081
2082 • bits (integer) -- Key length, or size (in bits) of the
2083 RSA modulus. It must be at least 1024, but 2048 is
2084 recommended. The FIPS standard only defines 1024, 2048
2085 and 3072.
2086
2087 • randfunc (callable) -- Function that returns random
2088 bytes. The default is Crypto.Random.get_ran‐
2089 dom_bytes().
2090
2091 • e (integer) -- Public RSA exponent. It must be an odd
2092 positive integer. It is typically a small number with
2093 very few ones in its binary representation. The FIPS
2094 standard requires the public exponent to be at least
2095 65537 (the default).
2096
2097 Returns: an RSA key object (RsaKey, with private key).
2098
2099 Crypto.PublicKey.RSA.import_key(extern_key, passphrase=None)
2100 Import an RSA key (public or private).
2101
2102 Parameters
2103
2104 • extern_key (string or byte string) --
2105
2106 The RSA key to import.
2107
2108 The following formats are supported for an RSA public
2109 key:
2110
2111 • X.509 certificate (binary or PEM format)
2112
2113 • X.509 subjectPublicKeyInfo DER SEQUENCE (binary or
2114 PEM encoding)
2115
2116 • PKCS#1 RSAPublicKey DER SEQUENCE (binary or PEM en‐
2117 coding)
2118
2119 • An OpenSSH line (e.g. the content of ~/.ssh/id_ecdsa,
2120 ASCII)
2121
2122 The following formats are supported for an RSA private
2123 key:
2124
2125 • PKCS#1 RSAPrivateKey DER SEQUENCE (binary or PEM en‐
2126 coding)
2127
2128 • PKCS#8 PrivateKeyInfo or EncryptedPrivateKeyInfo DER
2129 SEQUENCE (binary or PEM encoding)
2130
2131 • OpenSSH (text format, introduced in OpenSSH 6.5)
2132
2133 For details about the PEM encoding, see RFC1421/‐
2134 RFC1423.
2135
2136
2137 • passphrase (string or byte string) -- For private keys
2138 only, the pass phrase that encrypts the key.
2139
2140 Returns: An RSA key object (RsaKey).
2141
2142 Raises ValueError/IndexError/TypeError -- When the given key
2143 cannot be parsed (possibly because the pass
2144 phrase is wrong).
2145
2146 Crypto.PublicKey.RSA.oid = '1.2.840.113549.1.1.1'
2147 Object ID for the RSA encryption algorithm. This OID often indi‐
2148 cates a generic RSA key, even when such key will be actually
2149 used for digital signatures.
2150
2151 DSA
2152 DSA is a widespread public key signature algorithm. Its security is
2153 based on the discrete logarithm problem (DLP). Given a cyclic group, a
2154 generator g, and an element h, it is hard to find an integer x such
2155 that g^x = h. The problem is believed to be difficult, and it has been
2156 proved such (and therefore secure) for more than 30 years.
2157
2158 The group is actually a sub-group over the integers modulo p, with p
2159 prime. The sub-group order is q, which is prime too; it always holds
2160 that (p-1) is a multiple of q. The cryptographic strength is linked to
2161 the magnitude of p and q. The signer holds a value x (0<x<q-1) as pri‐
2162 vate key, and its public key (y where y=g^x \text{ mod } p) is distrib‐
2163 uted.
2164
2165 In 2017, a sufficient size is deemed to be 2048 bits for p and 256 bits
2166 for q. For more information, see the most recent ECRYPT report.
2167
2168 The algorithm can only be used for authentication (digital signature).
2169 DSA cannot be used for confidentiality (encryption).
2170
2171 The values (p,q,g) are called domain parameters; they are not sensitive
2172 but must be shared by both parties (the signer and the verifier). Dif‐
2173 ferent signers can share the same domain parameters with no security
2174 concerns.
2175
2176 The DSA signature is twice as big as the size of q (64 bytes if q is
2177 256 bit long).
2178
2179 This module provides facilities for generating new DSA keys and for
2180 constructing them from known components.
2181
2182 As an example, this is how you generate a new DSA key pair, save the
2183 public key in a file called public_key.pem, sign a message (with
2184 Crypto.Signature.DSS), and verify it:
2185
2186 >>> from Crypto.PublicKey import DSA
2187 >>> from Crypto.Signature import DSS
2188 >>> from Crypto.Hash import SHA256
2189 >>>
2190 >>> # Create a new DSA key
2191 >>> key = DSA.generate(2048)
2192 >>> f = open("public_key.pem", "w")
2193 >>> f.write(key.publickey().export_key())
2194 >>> f.close()
2195 >>>
2196 >>> # Sign a message
2197 >>> message = b"Hello"
2198 >>> hash_obj = SHA256.new(message)
2199 >>> signer = DSS.new(key, 'fips-186-3')
2200 >>> signature = signer.sign(hash_obj)
2201 >>>
2202 >>> # Load the public key
2203 >>> f = open("public_key.pem", "r")
2204 >>> hash_obj = SHA256.new(message)
2205 >>> pub_key = DSA.import_key(f.read())
2206 >>> verifier = DSS.new(pub_key, 'fips-186-3')
2207 >>>
2208 >>> # Verify the authenticity of the message
2209 >>> try:
2210 >>> verifier.verify(hash_obj, signature)
2211 >>> print "The message is authentic."
2212 >>> except ValueError:
2213 >>> print "The message is not authentic."
2214
2215 class Crypto.PublicKey.DSA.DsaKey(key_dict)
2216 Class defining an actual DSA key. Do not instantiate directly.
2217 Use generate(), construct() or import_key() instead.
2218
2219 Variables
2220
2221 • p (integer) -- DSA modulus
2222
2223 • q (integer) -- Order of the subgroup
2224
2225 • g (integer) -- Generator
2226
2227 • y (integer) -- Public key
2228
2229 • x (integer) -- Private key
2230
2231 Undocumented
2232 exportKey, publickey
2233
2234 domain()
2235 The DSA domain parameters.
2236
2237 Returns
2238 tuple : (p,q,g)
2239
2240 exportKey(format='PEM', pkcs8=None, passphrase=None, protec‐
2241 tion=None, randfunc=None)
2242 Export this DSA key.
2243
2244 Parameters
2245
2246 • format (string) --
2247
2248 The encoding for the output:
2249
2250 • 'PEM' (default). ASCII as per RFC1421/
2251 RFC1423.
2252
2253 • 'DER'. Binary ASN.1 encoding.
2254
2255 • 'OpenSSH'. ASCII one-liner as per RFC4253.
2256 Only suitable for public keys, not for private
2257 keys.
2258
2259
2260 • passphrase (string) -- Private keys only. The
2261 pass phrase to protect the output.
2262
2263 • pkcs8 (boolean) -- Private keys only. If True
2264 (default), the key is encoded with PKCS#8. If
2265 False, it is encoded in the custom
2266 OpenSSL/OpenSSH container.
2267
2268 • protection (string) --
2269
2270 Only in combination with a pass phrase. The en‐
2271 cryption scheme to use to protect the output.
2272
2273 If pkcs8 takes value True, this is the PKCS#8
2274 algorithm to use for deriving the secret and en‐
2275 crypting the private DSA key. For a complete
2276 list of algorithms, see Crypto.IO.PKCS8. The
2277 default is PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC.
2278
2279 If pkcs8 is False, the obsolete PEM encryption
2280 scheme is used. It is based on MD5 for key deri‐
2281 vation, and Triple DES for encryption. Parameter
2282 protection is then ignored.
2283
2284 The combination format='DER' and pkcs8=False is
2285 not allowed if a passphrase is present.
2286
2287
2288 • randfunc (callable) -- A function that returns
2289 random bytes. By default it is Crypto.Ran‐
2290 dom.get_random_bytes().
2291
2292 Returns
2293 the encoded key
2294
2295 Return type
2296 byte string
2297
2298 Raises ValueError -- when the format is unknown or when
2299 you try to encrypt a private
2300 key with DER format and OpenSSL/OpenSSH.
2301
2302 WARNING:
2303 If you don't provide a pass phrase, the private key
2304 will be exported in the clear!
2305
2306 export_key(format='PEM', pkcs8=None, passphrase=None, protec‐
2307 tion=None, randfunc=None)
2308 Export this DSA key.
2309
2310 Parameters
2311
2312 • format (string) --
2313
2314 The encoding for the output:
2315
2316 • 'PEM' (default). ASCII as per RFC1421/
2317 RFC1423.
2318
2319 • 'DER'. Binary ASN.1 encoding.
2320
2321 • 'OpenSSH'. ASCII one-liner as per RFC4253.
2322 Only suitable for public keys, not for private
2323 keys.
2324
2325
2326 • passphrase (string) -- Private keys only. The
2327 pass phrase to protect the output.
2328
2329 • pkcs8 (boolean) -- Private keys only. If True
2330 (default), the key is encoded with PKCS#8. If
2331 False, it is encoded in the custom
2332 OpenSSL/OpenSSH container.
2333
2334 • protection (string) --
2335
2336 Only in combination with a pass phrase. The en‐
2337 cryption scheme to use to protect the output.
2338
2339 If pkcs8 takes value True, this is the PKCS#8
2340 algorithm to use for deriving the secret and en‐
2341 crypting the private DSA key. For a complete
2342 list of algorithms, see Crypto.IO.PKCS8. The
2343 default is PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC.
2344
2345 If pkcs8 is False, the obsolete PEM encryption
2346 scheme is used. It is based on MD5 for key deri‐
2347 vation, and Triple DES for encryption. Parameter
2348 protection is then ignored.
2349
2350 The combination format='DER' and pkcs8=False is
2351 not allowed if a passphrase is present.
2352
2353
2354 • randfunc (callable) -- A function that returns
2355 random bytes. By default it is Crypto.Ran‐
2356 dom.get_random_bytes().
2357
2358 Returns
2359 the encoded key
2360
2361 Return type
2362 byte string
2363
2364 Raises ValueError -- when the format is unknown or when
2365 you try to encrypt a private
2366 key with DER format and OpenSSL/OpenSSH.
2367
2368 WARNING:
2369 If you don't provide a pass phrase, the private key
2370 will be exported in the clear!
2371
2372 has_private()
2373 Whether this is a DSA private key
2374
2375 public_key()
2376 A matching DSA public key.
2377
2378 Returns
2379 a new DsaKey object
2380
2381 publickey()
2382 A matching DSA public key.
2383
2384 Returns
2385 a new DsaKey object
2386
2387 Crypto.PublicKey.DSA.construct(tup, consistency_check=True)
2388 Construct a DSA key from a tuple of valid DSA components.
2389
2390 Parameters
2391
2392 • tup (tuple) --
2393
2394 A tuple of long integers, with 4 or 5 items in the fol‐
2395 lowing order:
2396
2397 1. Public key (y).
2398
2399 2. Sub-group generator (g).
2400
2401 3. Modulus, finite field order (p).
2402
2403 4. Sub-group order (q).
2404
2405 5. Private key (x). Optional.
2406
2407
2408 • consistency_check (boolean) -- If True, the library
2409 will verify that the provided components fulfil the
2410 main DSA properties.
2411
2412 Raises ValueError -- when the key being imported fails the most
2413 basic DSA validity checks.
2414
2415 Returns
2416 a DSA key object
2417
2418 Return type
2419 DsaKey
2420
2421 Crypto.PublicKey.DSA.generate(bits, randfunc=None, domain=None)
2422 Generate a new DSA key pair.
2423
2424 The algorithm follows Appendix A.1/A.2 and B.1 of FIPS 186-4,
2425 respectively for domain generation and key pair generation.
2426
2427 Parameters
2428
2429 • bits (integer) -- Key length, or size (in bits) of the
2430 DSA modulus p. It must be 1024, 2048 or 3072.
2431
2432 • randfunc (callable) -- Random number generation func‐
2433 tion; it accepts a single integer N and return a string
2434 of random data N bytes long. If not specified,
2435 Crypto.Random.get_random_bytes() is used.
2436
2437 • domain (tuple) -- The DSA domain parameters p, q and g
2438 as a list of 3 integers. Size of p and q must comply to
2439 FIPS 186-4. If not specified, the parameters are cre‐
2440 ated anew.
2441
2442 Returns
2443 a new DSA key object
2444
2445 Return type
2446 DsaKey
2447
2448 Raises ValueError -- when bits is too little, too big, or not a
2449 multiple of 64.
2450
2451 Crypto.PublicKey.DSA.import_key(extern_key, passphrase=None)
2452 Import a DSA key.
2453
2454 Parameters
2455
2456 • extern_key (string or byte string) --
2457
2458 The DSA key to import.
2459
2460 The following formats are supported for a DSA public
2461 key:
2462
2463 • X.509 certificate (binary DER or PEM)
2464
2465 • X.509 subjectPublicKeyInfo (binary DER or PEM)
2466
2467 • OpenSSH (ASCII one-liner, see RFC4253)
2468
2469 The following formats are supported for a DSA private
2470 key:
2471
2472 • PKCS#8 PrivateKeyInfo or EncryptedPrivateKeyInfo DER
2473 SEQUENCE (binary or PEM)
2474
2475 • OpenSSL/OpenSSH custom format (binary or PEM)
2476
2477 For details about the PEM encoding, see RFC1421/‐
2478 RFC1423.
2479
2480
2481 • passphrase (string) --
2482
2483 In case of an encrypted private key, this is the pass
2484 phrase from which the decryption key is derived.
2485
2486 Encryption may be applied either at the PKCS#8 or at
2487 the PEM level.
2488
2489
2490 Returns
2491 a DSA key object
2492
2493 Return type
2494 DsaKey
2495
2496 Raises ValueError -- when the given key cannot be parsed (possi‐
2497 bly because
2498 the pass phrase is wrong).
2499
2500 ECC
2501 ECC (Elliptic Curve Cryptography) is a modern and efficient type of
2502 public key cryptography. Its security is based on the difficulty to
2503 solve discrete logarithms on the field defined by specific equations
2504 computed over a curve.
2505
2506 ECC can be used to create digital signatures or to perform a key ex‐
2507 change.
2508
2509 Compared to traditional algorithms like RSA, an ECC key is signifi‐
2510 cantly smaller at the same security level. For instance, a 3072-bit
2511 RSA key takes 768 bytes whereas the equally strong NIST P-256 private
2512 key only takes 32 bytes (that is, 256 bits).
2513
2514 This module provides mechanisms for generating new ECC keys, exporting
2515 and importing them using widely supported formats like PEM or DER.
2516
2517 ┌───────────┬────────────────────────────┐
2518 │Curve │ Possible identifiers │
2519 ├───────────┼────────────────────────────┤
2520 │NIST P-256 │ 'NIST P-256', 'p256', │
2521 │ │ 'P-256', 'prime256v1', │
2522 │ │ 'secp256r1' │
2523 ├───────────┼────────────────────────────┤
2524 │NIST P-384 │ 'NIST P-384', 'p384', │
2525 │ │ 'P-384', 'prime384v1', │
2526 │ │ 'secp384r1' │
2527 └───────────┴────────────────────────────┘
2528
2529
2530
2531
2532 │NIST P-521 │ 'NIST P-521', 'p521', │
2533 │ │ 'P-521', 'prime521v1', │
2534 │ │ 'secp521r1' │
2535 └───────────┴────────────────────────────┘
2536
2537 For more information about each NIST curve see FIPS 186-4, Section
2538 D.1.2.
2539
2540 The following example demonstrates how to generate a new ECC key, ex‐
2541 port it, and subsequently reload it back into the application:
2542
2543 >>> from Crypto.PublicKey import ECC
2544 >>>
2545 >>> key = ECC.generate(curve='P-256')
2546 >>>
2547 >>> f = open('myprivatekey.pem','wt')
2548 >>> f.write(key.export_key(format='PEM'))
2549 >>> f.close()
2550 ...
2551 >>> f = open('myprivatekey.pem','rt')
2552 >>> key = ECC.import_key(f.read())
2553
2554 The ECC key can be used to perform or verify ECDSA signatures, using
2555 the module Crypto.Signature.DSS.
2556
2557 class Crypto.PublicKey.ECC.EccKey(**kwargs)
2558 Class defining an ECC key. Do not instantiate directly. Use
2559 generate(), construct() or import_key() instead.
2560
2561 Variables
2562
2563 • curve (string) -- The name of the ECC as defined in
2564 curve_names.
2565
2566 • pointQ (EccPoint) -- an ECC point representating the
2567 public component
2568
2569 • d (integer) -- A scalar representating the private com‐
2570 ponent
2571
2572 export_key(**kwargs)
2573 Export this ECC key.
2574
2575 Parameters
2576
2577 • format (string) --
2578
2579 The format to use for encoding the key:
2580
2581 • 'DER'. The key will be encoded in ASN.1 DER
2582 format (binary). For a public key, the ASN.1
2583 subjectPublicKeyInfo structure defined in
2584 RFC5480 will be used. For a private key, the
2585 ASN.1 ECPrivateKey structure defined in
2586 RFC5915 is used instead (possibly within a
2587 PKCS#8 envelope, see the use_pkcs8 flag be‐
2588 low).
2589
2590 • 'PEM'. The key will be encoded in a PEM enve‐
2591 lope (ASCII).
2592
2593 • 'OpenSSH'. The key will be encoded in the
2594 OpenSSH format (ASCII, public keys only).
2595
2596
2597 • passphrase (byte string or string) -- The
2598 passphrase to use for protecting the private
2599 key.
2600
2601 • use_pkcs8 (boolean) --
2602
2603 Only relevant for private keys.
2604
2605 If True (default and recommended), the PKCS#8
2606 representation will be used.
2607
2608 If False, the much weaker PEM encryption mecha‐
2609 nism will be used.
2610
2611
2612 • protection (string) -- When a private key is ex‐
2613 ported with password-protection and PKCS#8 (both
2614 DER and PEM formats), this parameter MUST be
2615 present and be a valid algorithm supported by
2616 Crypto.IO.PKCS8. It is recommended to use
2617 PBKDF2WithHMAC-SHA1AndAES128-CBC.
2618
2619 • compress (boolean) --
2620
2621 If True, a more compact representation of the
2622 public key with the X-coordinate only is used.
2623
2624 If False (default), the full public key will be
2625 exported.
2626
2627
2628 WARNING:
2629 If you don't provide a passphrase, the private key
2630 will be exported in the clear!
2631
2632 NOTE:
2633 When exporting a private key with password-protection
2634 and PKCS#8 (both DER and PEM formats), any extra pa‐
2635 rameters to export_key() will be passed to
2636 Crypto.IO.PKCS8.
2637
2638 Returns
2639 A multi-line string (for PEM and OpenSSH) or bytes
2640 (for DER) with the encoded key.
2641
2642 has_private()
2643 True if this key can be used for making signatures or de‐
2644 crypting data.
2645
2646 public_key()
2647 A matching ECC public key.
2648
2649 Returns
2650 a new EccKey object
2651
2652 class Crypto.PublicKey.ECC.EccPoint(x, y, curve='p256')
2653 A class to abstract a point over an Elliptic Curve.
2654
2655 The class support special methods for:
2656
2657 • Adding two points: R = S + T
2658
2659 • In-place addition: S += T
2660
2661 • Negating a point: R = -T
2662
2663 • Comparing two points: if S == T: ...
2664
2665 • Multiplying a point by a scalar: R = S*k
2666
2667 • In-place multiplication by a scalar: T *= k
2668
2669 Variables
2670
2671 • x (integer) -- The affine X-coordinate of the ECC point
2672
2673 • y (integer) -- The affine Y-coordinate of the ECC point
2674
2675 • xy -- The tuple with X- and Y- coordinates
2676
2677 copy() Return a copy of this point.
2678
2679 double()
2680 Double this point (in-place operation).
2681
2682 Return EccPoint : this same object (to enable chaining)
2683
2684 is_point_at_infinity()
2685 True if this is the point-at-infinity.
2686
2687 point_at_infinity()
2688 Return the point-at-infinity for the curve this point is
2689 on.
2690
2691 size_in_bits()
2692 Size of each coordinate, in bits.
2693
2694 size_in_bytes()
2695 Size of each coordinate, in bytes.
2696
2697 exception Crypto.PublicKey.ECC.UnsupportedEccFeature
2698
2699 Crypto.PublicKey.ECC.construct(**kwargs)
2700 Build a new ECC key (private or public) starting from some base
2701 components.
2702
2703 Parameters
2704
2705 • curve (string) -- Mandatory. It must be a curve name
2706 defined in curve_names.
2707
2708 • d (integer) -- Only for a private key. It must be in
2709 the range [1..order-1].
2710
2711 • point_x (integer) -- Mandatory for a public key. X co‐
2712 ordinate (affine) of the ECC point.
2713
2714 • point_y (integer) -- Mandatory for a public key. Y co‐
2715 ordinate (affine) of the ECC point.
2716
2717 Returns
2718 a new ECC key object
2719
2720 Return type
2721 EccKey
2722
2723 Crypto.PublicKey.ECC.generate(**kwargs)
2724 Generate a new private key on the given curve.
2725
2726 Parameters
2727
2728 • curve (string) -- Mandatory. It must be a curve name
2729 defined in curve_names.
2730
2731 • randfunc (callable) -- Optional. The RNG to read ran‐
2732 domness from. If None, Crypto.Random.get_ran‐
2733 dom_bytes() is used.
2734
2735 Crypto.PublicKey.ECC.import_key(encoded, passphrase=None)
2736 Import an ECC key (public or private).
2737
2738 Parameters
2739
2740 • encoded (bytes or multi-line string) --
2741
2742 The ECC key to import.
2743
2744 An ECC public key can be:
2745
2746 • An X.509 certificate, binary (DER) or ASCII (PEM)
2747
2748 • An X.509 subjectPublicKeyInfo, binary (DER) or ASCII
2749 (PEM)
2750
2751 • An OpenSSH line (e.g. the content of ~/.ssh/id_ecdsa,
2752 ASCII)
2753
2754 An ECC private key can be:
2755
2756 • In binary format (DER, see section 3 of RFC5915 or
2757 PKCS#8)
2758
2759 • In ASCII format (PEM or OpenSSH 6.5+)
2760
2761 Private keys can be in the clear or password-protected.
2762
2763 For details about the PEM encoding, see RFC1421/‐
2764 RFC1423.
2765
2766
2767 • passphrase (byte string) -- The passphrase to use for
2768 decrypting a private key. Encryption may be applied
2769 protected at the PEM level or at the PKCS#8 level.
2770 This parameter is ignored if the key in input is not
2771 encrypted.
2772
2773 Returns
2774 a new ECC key object
2775
2776 Return type
2777 EccKey
2778
2779 Raises ValueError -- when the given key cannot be parsed (possi‐
2780 bly because
2781 the pass phrase is wrong).
2782
2783 • RSA keys
2784
2785 • DSA keys
2786
2787 • Elliptic Curve keys
2788
2789 Obsolete key type
2790 El Gamal
2791 WARNING:
2792 Even though ElGamal algorithms are in theory reasonably secure, in
2793 practice there are no real good reasons to prefer them to rsa in‐
2794 stead.
2795
2796 Signature algorithm
2797 The security of the ElGamal signature scheme is based (like DSA) on the
2798 discrete logarithm problem (DLP). Given a cyclic group, a generator g,
2799 and an element h, it is hard to find an integer x such that g^x = h.
2800
2801 The group is the largest multiplicative sub-group of the integers mod‐
2802 ulo p, with p prime. The signer holds a value x (0<x<p-1) as private
2803 key, and its public key (y where y=g^x \text{ mod } p) is distributed.
2804
2805 The ElGamal signature is twice as big as p.
2806
2807 Encryption algorithm
2808 The security of the ElGamal encryption scheme is based on the computa‐
2809 tional Diffie-Hellman problem (CDH). Given a cyclic group, a generator
2810 g, and two integers a and b, it is difficult to find the element g^{ab}
2811 when only g^a and g^b are known, and not a and b.
2812
2813 As before, the group is the largest multiplicative sub-group of the in‐
2814 tegers modulo p, with p prime. The receiver holds a value a (0<a<p-1)
2815 as private key, and its public key (b where b=g^a) is given to the
2816 sender.
2817
2818 The ElGamal ciphertext is twice as big as p.
2819
2820 Domain parameters
2821 For both signature and encryption schemes, the values (p,g) are called
2822 domain parameters. They are not sensitive but must be distributed to
2823 all parties (senders and receivers). Different signers can share the
2824 same domain parameters, as can different recipients of encrypted mes‐
2825 sages.
2826
2827 Security
2828 Both DLP and CDH problem are believed to be difficult, and they have
2829 been proved such (and therefore secure) for more than 30 years.
2830
2831 The cryptographic strength is linked to the magnitude of p. In 2017, a
2832 sufficient size for p is deemed to be 2048 bits. For more information,
2833 see the most recent ECRYPT report.
2834
2835 The signature is four times larger than the equivalent DSA, and the ci‐
2836 phertext is two times larger than the equivalent RSA.
2837
2838 Functionality
2839 This module provides facilities for generating new ElGamal keys and
2840 constructing them from known components.
2841
2842 class Crypto.PublicKey.ElGamal.ElGamalKey(randfunc=None)
2843 Class defining an ElGamal key. Do not instantiate directly.
2844 Use generate() or construct() instead.
2845
2846 Variables
2847
2848 • p -- Modulus
2849
2850 • g -- Generator
2851
2852 • y (integer) -- Public key component
2853
2854 • x (integer) -- Private key component
2855
2856 has_private()
2857 Whether this is an ElGamal private key
2858
2859 publickey()
2860 A matching ElGamal public key.
2861
2862 Returns
2863 a new ElGamalKey object
2864
2865 Crypto.PublicKey.ElGamal.construct(tup)
2866 Construct an ElGamal key from a tuple of valid ElGamal compo‐
2867 nents.
2868
2869 The modulus p must be a prime. The following conditions must
2870 apply:
2871
2872 \begin{align}
2873 &1 < g < p-1 \\ &g^{p-1} = 1 \text{ mod } 1 \\ &1 < x < p-1 \\
2874 &g^x = y \text{ mod } p \end{align}
2875
2876 Parameters
2877 tup (tuple) --
2878
2879 A tuple with either 3 or 4 integers, in the following or‐
2880 der:
2881
2882 1. Modulus (p).
2883
2884 2. Generator (g).
2885
2886 3. Public key (y).
2887
2888 4. Private key (x). Optional.
2889
2890
2891 Raises ValueError -- when the key being imported fails the most
2892 basic ElGamal validity checks.
2893
2894 Returns
2895 an ElGamalKey object
2896
2897 Crypto.PublicKey.ElGamal.generate(bits, randfunc)
2898 Randomly generate a fresh, new ElGamal key.
2899
2900 The key will be safe for use for both encryption and signature
2901 (although it should be used for only one purpose).
2902
2903 Parameters
2904
2905 • bits (int) -- Key length, or size (in bits) of the mod‐
2906 ulus p. The recommended value is 2048.
2907
2908 • randfunc (callable) -- Random number generation func‐
2909 tion; it should accept a single integer N and return a
2910 string of random N random bytes.
2911
2912 Returns
2913 an ElGamalKey object
2914
2915 • ElGamal keys
2916
2917 Crypto.Protocol package
2918 Key Derivation Functions
2919 This module contains a collection of standard key derivation functions.
2920
2921 A key derivation function derives one or more secondary secret keys
2922 from one primary secret (a master key or a pass phrase).
2923
2924 This is typically done to insulate the secondary keys from each other,
2925 to avoid that leakage of a secondary key compromises the security of
2926 the master key, or to thwart attacks on pass phrases (e.g. via rainbow
2927 tables).
2928
2929 PBKDF2
2930 PBKDF2 is the most widespread algorithm for deriving keys from a pass‐
2931 word, originally defined in version 2.0 of the PKCS#5 standard or in
2932 RFC2898.
2933
2934 It is computationally expensive (a property that can be tuned via the
2935 count parameter) so as to thwart dictionary and rainbow tables attacks.
2936 However, it uses a very limited amount of RAM which makes it insuffi‐
2937 ciently protected against advanced and motivated adversaries that can
2938 leverage GPUs.
2939
2940 New applications and protocols should use scrypt or bcrypt instead.
2941
2942 For example, if you need to derive two AES256 keys:
2943
2944 from Crypto.Protocol.KDF import PBKDF2
2945 from Crypto.Hash import SHA512
2946 from Crypto.Random import get_random_bytes
2947
2948 password = b'my super secret'
2949 salt = get_random_bytes(16)
2950 keys = PBKDF2(password, salt, 64, count=1000000, hmac_hash_module=SHA512)
2951 key1 = keys[:32]
2952 key2 = keys[32:]
2953
2954 Crypto.Protocol.KDF.PBKDF2(password, salt, dkLen=16, count=1000,
2955 prf=None, hmac_hash_module=None)
2956 Derive one or more keys from a password (or passphrase).
2957
2958 This function performs key derivation according to the PKCS#5
2959 standard (v2.0).
2960
2961 Parameters
2962
2963 • password (string or byte string) -- The secret password
2964 to generate the key from.
2965
2966 • salt (string or byte string) -- A (byte) string to use
2967 for better protection from dictionary attacks. This
2968 value does not need to be kept secret, but it should be
2969 randomly chosen for each derivation. It is recommended
2970 to use at least 16 bytes.
2971
2972 • dkLen (integer) --
2973
2974 The cumulative length of the keys to produce.
2975
2976 Due to a flaw in the PBKDF2 design, you should not re‐
2977 quest more bytes than the prf can output. For instance,
2978 dkLen should not exceed 20 bytes in combination with
2979 HMAC-SHA1.
2980
2981
2982 • count (integer) --
2983
2984 The number of iterations to carry out. The higher the
2985 value, the slower and the more secure the function be‐
2986 comes.
2987
2988 You should find the maximum number of iterations that
2989 keeps the key derivation still acceptable on the slow‐
2990 est hardware you must support.
2991
2992 Although the default value is 1000, it is recommended
2993 to use at least 1000000 (1 million) iterations.
2994
2995
2996 • prf (callable) -- A pseudorandom function. It must be a
2997 function that returns a pseudorandom byte string from
2998 two parameters: a secret and a salt. The slower the
2999 algorithm, the more secure the derivation function. If
3000 not specified, HMAC-SHA1 is used.
3001
3002 • hmac_hash_module (module) -- A module from Crypto.Hash
3003 implementing a Merkle-Damgard cryptographic hash, which
3004 PBKDF2 must use in combination with HMAC. This parame‐
3005 ter is mutually exclusive with prf.
3006
3007 Returns
3008 A byte string of length dkLen that can be used as key ma‐
3009 terial. If you want multiple keys, just break up this
3010 string into segments of the desired length.
3011
3012 scrypt
3013 scrypt is a password-based key derivation function created by Colin
3014 Percival, described in his paper "Stronger key derivation via sequen‐
3015 tial memory-hard functions" and in RFC7914.
3016
3017 In addition to being computationally expensive, it is also memory in‐
3018 tensive and therefore more secure against the risk of custom ASICs.
3019
3020 Example:
3021
3022 from Crypto.Protocol.KDF import scrypt
3023 from Crypto.Random import get_random_bytes
3024
3025 password = b'my super secret'
3026 salt = get_random_bytes(16)
3027 key = scrypt(password, salt, 16, N=2**14, r=8, p=1)
3028
3029 Crypto.Protocol.KDF.scrypt(password, salt, key_len, N, r, p,
3030 num_keys=1)
3031 Derive one or more keys from a passphrase.
3032
3033 Parameters
3034
3035 • password (string) -- The secret pass phrase to generate
3036 the keys from.
3037
3038 • salt (string) -- A string to use for better protection
3039 from dictionary attacks. This value does not need to
3040 be kept secret, but it should be randomly chosen for
3041 each derivation. It is recommended to be at least 16
3042 bytes long.
3043
3044 • key_len (integer) -- The length in bytes of every de‐
3045 rived key.
3046
3047 • N (integer) -- CPU/Memory cost parameter. It must be a
3048 power of 2 and less than 2^{32}.
3049
3050 • r (integer) -- Block size parameter.
3051
3052 • p (integer) -- Parallelization parameter. It must be
3053 no greater than (2^{32}-1)/(4r).
3054
3055 • num_keys (integer) -- The number of keys to derive. Ev‐
3056 ery key is key_len bytes long. By default, only 1 key
3057 is generated. The maximum cumulative length of all
3058 keys is (2^{32}-1)*32 (that is, 128TB).
3059
3060 A good choice of parameters (N, r , p) was suggested by Colin
3061 Percival in his presentation in 2009:
3062
3063 • ( 2¹⁴, 8, 1 ) for interactive logins (≤100ms)
3064
3065 • ( 2²⁰, 8, 1 ) for file encryption (≤5s)
3066
3067 Returns
3068 A byte string or a tuple of byte strings.
3069
3070 bcrypt
3071 bcrypt is a password hashing function designed by Niels Provos and
3072 David Mazières.
3073
3074 In addition to being computationally expensive, it is also memory in‐
3075 tensive and therefore more secure against the risk of custom ASICs.
3076
3077 This implementation only supports bcrypt hashes with prefix $2a.
3078
3079 By design, bcrypt only accepts passwords up to 72 byte long. If you
3080 want to hash passwords with no restrictions on their length, it is com‐
3081 mon practice to apply a cryptographic hash and then BASE64-encode For
3082 instance:
3083
3084 from base64 import b64encode
3085 from Crypto.Hash import SHA256
3086 from Crypto.Protocol.KDF import bcrypt
3087
3088 password = b"test"
3089 b64pwd = b64encode(SHA256.new(password).digest())
3090 bcrypt_hash = bcrypt(b64pwd, 12)
3091
3092 and to check them:
3093
3094 from base64 import b64encode
3095 from Crypto.Hash import SHA256
3096 from Crypto.Protocol.KDF import bcrypt
3097
3098 password_to_test = b"test"
3099 try:
3100 b64pwd = b64encode(SHA256.new(password).digest())
3101 bcrypt_check(b64pwd, bcrypt_hash)
3102 except ValueError:
3103 print("Incorrect password")
3104
3105 Crypto.Protocol.KDF.bcrypt(password, cost, salt=None)
3106 Hash a password into a key, using the OpenBSD bcrypt protocol.
3107
3108 Parameters
3109
3110 • password (byte string or string) -- The secret password
3111 or pass phrase. It must be at most 72 bytes long. It
3112 must not contain the zero byte. Unicode strings will
3113 be encoded as UTF-8.
3114
3115 • cost (integer) -- The exponential factor that makes it
3116 slower to compute the hash. It must be in the range 4
3117 to 31. A value of at least 12 is recommended.
3118
3119 • salt (byte string) -- Optional. Random byte string to
3120 thwarts dictionary and rainbow table attacks. It must
3121 be 16 bytes long. If not passed, a random value is
3122 generated.
3123
3124 Return (byte string):
3125 The bcrypt hash
3126
3127 Raises ValueError -- if password is longer than 72 bytes or if
3128 it contains the zero byte
3129
3130 Crypto.Protocol.KDF.bcrypt_check(password, bcrypt_hash)
3131 Verify if the provided password matches the given bcrypt hash.
3132
3133 Parameters
3134
3135 • password (byte string or string) -- The secret password
3136 or pass phrase to test. It must be at most 72 bytes
3137 long. It must not contain the zero byte. Unicode
3138 strings will be encoded as UTF-8.
3139
3140 • bcrypt_hash (byte string, bytearray) -- The reference
3141 bcrypt hash the password needs to be checked against.
3142
3143 Raises ValueError -- if the password does not match
3144
3145 HKDF
3146 The HMAC-based Extract-and-Expand key derivation function (HKDF) was
3147 designed by Hugo Krawczyk. It is standardized in RFC 5869 and in NIST
3148 SP-800 56C.
3149
3150 This KDF is not suitable for deriving keys from a password or for key
3151 stretching.
3152
3153 Example, for deriving two AES256 keys:
3154
3155 from Crypto.Protocol.KDF import HKDF
3156 from Crypto.Hash import SHA512
3157 from Crypto.Random import get_random_bytes
3158
3159 salt = get_random_bytes(16)
3160 key1, key2 = HKDF(master_secret, 32, salt, SHA512, 2)
3161
3162 Crypto.Protocol.KDF.HKDF(master, key_len, salt, hashmod, num_keys=1,
3163 context=None)
3164 Derive one or more keys from a master secret using the
3165 HMAC-based KDF defined in RFC5869.
3166
3167 Parameters
3168
3169 • master (byte string) -- The unguessable value used by
3170 the KDF to generate the other keys. It must be a
3171 high-entropy secret, though not necessarily uniform.
3172 It must not be a password.
3173
3174 • salt (byte string) -- A non-secret, reusable value that
3175 strengthens the randomness extraction step. Ideally,
3176 it is as long as the digest size of the chosen hash.
3177 If empty, a string of zeroes in used.
3178
3179 • key_len (integer) -- The length in bytes of every de‐
3180 rived key.
3181
3182 • hashmod (module) -- A cryptographic hash algorithm from
3183 Crypto.Hash. Crypto.Hash.SHA512 is a good choice.
3184
3185 • num_keys (integer) -- The number of keys to derive. Ev‐
3186 ery key is key_len bytes long. The maximum cumulative
3187 length of all keys is 255 times the digest size.
3188
3189 • context (byte string) -- Optional identifier describing
3190 what the keys are used for.
3191
3192 Returns
3193 A byte string or a tuple of byte strings.
3194
3195 PBKDF1
3196 PBKDF1 is an old key derivation function defined in version 2.0 of the
3197 PKCS#5 standard (v1.5) or in RFC2898.
3198
3199 WARNING:
3200 Newer applications should use the more secure and versatile scrypt
3201 instead.
3202
3203 Crypto.Protocol.KDF.PBKDF1(password, salt, dkLen, count=1000,
3204 hashAlgo=None)
3205 Derive one key from a password (or passphrase).
3206
3207 This function performs key derivation according to an old ver‐
3208 sion of the PKCS#5 standard (v1.5) or RFC2898.
3209
3210 Parameters
3211
3212 • password (string) -- The secret password to generate
3213 the key from.
3214
3215 • salt (byte string) -- An 8 byte string to use for bet‐
3216 ter protection from dictionary attacks. This value
3217 does not need to be kept secret, but it should be ran‐
3218 domly chosen for each derivation.
3219
3220 • dkLen (integer) -- The length of the desired key. The
3221 default is 16 bytes, suitable for instance for
3222 Crypto.Cipher.AES.
3223
3224 • count (integer) -- The number of iterations to carry
3225 out. The recommendation is 1000 or more.
3226
3227 • hashAlgo (module) -- The hash algorithm to use, as a
3228 module or an object from the Crypto.Hash package. The
3229 digest length must be no shorter than dkLen. The de‐
3230 fault algorithm is Crypto.Hash.SHA1.
3231
3232 Returns
3233 A byte string of length dkLen that can be used as key.
3234
3235 Secret Sharing Schemes
3236 This module implements the Shamir's secret sharing protocol described
3237 in the paper "How to share a secret".
3238
3239 The secret can be split into an arbitrary number of shares (n), such
3240 that it is sufficient to collect just k of them to reconstruct it (k <
3241 n). For instance, one may want to grant 16 people the ability to ac‐
3242 cess a system with a pass code, at the condition that at least 3 of
3243 them are present at the same time. As they join their shares, the pass
3244 code is revealed. In that case, n=16 and k=3.
3245
3246 In the Shamir's secret sharing scheme, the n shares are created by
3247 first defining a polynomial of degree k-1:
3248
3249 q(x) = a_0 + a_1 x + a_2 x^2 + \ldots + a_{k-1} x^{k-1}
3250
3251 The coefficient a_0 is fixed with the secret value. The coefficients
3252 a_1 \ldots a_{k-1} are random and they are discarded as soon as the
3253 shares are created.
3254
3255 Each share is a pair (x_i, y_i), where x_i is an arbitrary but unique
3256 number assigned to the share's recipient and y_i=q(x_i).
3257
3258 This implementation has the following properties:
3259
3260 • The secret is a byte string of 16 bytes (e.g. an AES 128 key).
3261
3262 • Each share is a byte string of 16 bytes.
3263
3264 • The recipients of the shares are assigned an integer starting from 1
3265 (share number x_i).
3266
3267 • The polynomial q(x) is defined over the field GF(2^{128}) with the
3268 same irriducible polynomial as used in AES-GCM: 1 + x + x^2 + x^7 +
3269 x^{128}.
3270
3271 • It can be compatible with the popular ssss tool when used with the
3272 128 bit security level and no dispersion: the command line arguments
3273 must include -s 128 -D. Note that ssss uses a slightly different
3274 polynomial:
3275
3276 r(x) = a_0 + a_1 x + a_2 x^2 + \ldots + a_{k-1} x^{k-1} + x^k
3277
3278 which requires you to specify ssss=True when calling split() and com‐
3279 bine().
3280
3281 Each recipient needs to hold both the share number (x_i, which is not
3282 confidential) and the secret (which needs to be protected securely).
3283
3284 As an example, the following code shows how to protect a file meant for
3285 5 people, in such a way that any 2 of them are sufficient to reassemble
3286 it:
3287
3288 >>> from binascii import hexlify
3289 >>> from Crypto.Cipher import AES
3290 >>> from Crypto.Random import get_random_bytes
3291 >>> from Crypto.Protocol.SecretSharing import Shamir
3292 >>>
3293 >>> key = get_random_bytes(16)
3294 >>> shares = Shamir.split(2, 5, key)
3295 >>> for idx, share in shares:
3296 >>> print "Index #%d: %s" % (idx, hexlify(share))
3297 >>>
3298 >>> with open("clear.txt", "rb") as fi, open("enc.txt", "wb") as fo:
3299 >>> cipher = AES.new(key, AES.MODE_EAX)
3300 >>> ct, tag = cipher.encrypt(fi.read()), cipher.digest()
3301 >>> fo.write(nonce + tag + ct)
3302
3303 Each person can be given one share and the encrypted file.
3304
3305 When 2 people gather together with their shares, they can decrypt the
3306 file:
3307
3308 >>> from binascii import unhexlify
3309 >>> from Crypto.Cipher import AES
3310 >>> from Crypto.Protocol.SecretSharing import Shamir
3311 >>>
3312 >>> shares = []
3313 >>> for x in range(2):
3314 >>> in_str = raw_input("Enter index and share separated by comma: ")
3315 >>> idx, share = [ strip(s) for s in in_str.split(",") ]
3316 >>> shares.append((idx, unhexlify(share)))
3317 >>> key = Shamir.combine(shares)
3318 >>>
3319 >>> with open("enc.txt", "rb") as fi:
3320 >>> nonce, tag = [ fi.read(16) for x in range(2) ]
3321 >>> cipher = AES.new(key, AES.MODE_EAX, nonce)
3322 >>> try:
3323 >>> result = cipher.decrypt(fi.read())
3324 >>> cipher.verify(tag)
3325 >>> with open("clear2.txt", "wb") as fo:
3326 >>> fo.write(result)
3327 >>> except ValueError:
3328 >>> print "The shares were incorrect"
3329
3330 ATTENTION:
3331 Reconstruction may succeed but still produce the incorrect secret if
3332 any of the presented shares is incorrect (due to data corruption or
3333 to a malicious participant).
3334
3335 It is extremely important to also use an authentication mechanism
3336 (such as the EAX cipher mode in the example).
3337
3338 class Crypto.Protocol.SecretSharing.Shamir
3339 Shamir's secret sharing scheme.
3340
3341 A secret is split into n shares, and it is sufficient to collect
3342 k of them to reconstruct the secret.
3343
3344 static combine(shares, ssss=False)
3345 Recombine a secret, if enough shares are presented.
3346
3347 Parameters
3348
3349 • shares (tuples) -- The k tuples, each containin
3350 the index (an integer) and the share (a byte
3351 string, 16 bytes long) that were assigned to a
3352 participant.
3353
3354 • ssss (bool) -- If True, the shares were produced
3355 by the ssss utility. Default: False.
3356
3357 Returns
3358 The original secret, as a byte string (16 bytes
3359 long).
3360
3361 static split(k, n, secret, ssss=False)
3362 Split a secret into n shares.
3363
3364 The secret can be reconstructed later using just k shares
3365 out of the original n. Each share must be kept confiden‐
3366 tial to the person it was assigned to.
3367
3368 Each share is associated to an index (starting from 1).
3369
3370 Parameters
3371
3372 • k (integer) -- The sufficient number of shares
3373 to reconstruct the secret (k < n).
3374
3375 • n (integer) -- The number of shares that this
3376 method will create.
3377
3378 • secret (byte string) -- A byte string of 16
3379 bytes (e.g. the AES 128 key).
3380
3381 • ssss (bool) -- If True, the shares can be used
3382 with the ssss utility. Default: False.
3383
3384 Return (tuples):
3385 n tuples. A tuple is meant for each participant
3386 and it contains two items:
3387
3388 1. the unique index (an integer)
3389
3390 2. the share (a byte string, 16 bytes)
3391
3392 • kdf
3393
3394 • ss
3395
3396 Crypto.IO package
3397 Modules for reading and writing cryptographic data.
3398
3399 • pem
3400
3401 • pkcs8
3402
3403 PEM
3404 Set of functions for encapsulating data according to the PEM format.
3405
3406 PEM (Privacy Enhanced Mail) was an IETF standard for securing emails
3407 via a Public Key Infrastructure. It is specified in RFC 1421-1424.
3408
3409 Even though it has been abandoned, the simple message encapsulation it
3410 defined is still widely used today for encoding binary cryptographic
3411 objects like keys and certificates into text.
3412
3413 Crypto.IO.PEM.decode(pem_data, passphrase=None)
3414 Decode a PEM block into binary.
3415
3416 Parameters
3417
3418 • pem_data (string) -- The PEM block.
3419
3420 • passphrase (byte string) -- If given and the PEM block
3421 is encrypted, the key will be derived from the
3422 passphrase.
3423
3424 Returns
3425 A tuple with the binary data, the marker string, and a
3426 boolean to indicate if decryption was performed.
3427
3428 Raises ValueError -- if decoding fails, if the PEM file is en‐
3429 crypted and no passphrase has
3430 been provided or if the passphrase is incorrect.
3431
3432 Crypto.IO.PEM.encode(data, marker, passphrase=None, randfunc=None)
3433 Encode a piece of binary data into PEM format.
3434
3435 Parameters
3436
3437 • data (byte string) -- The piece of binary data to en‐
3438 code.
3439
3440 • marker (string) -- The marker for the PEM block (e.g.
3441 "PUBLIC KEY"). Note that there is no official master
3442 list for all allowed markers. Still, you can refer to
3443 the OpenSSL source code.
3444
3445 • passphrase (byte string) -- If given, the PEM block
3446 will be encrypted. The key is derived from the
3447 passphrase.
3448
3449 • randfunc (callable) -- Random number generation func‐
3450 tion; it accepts an integer N and returns a byte string
3451 of random data, N bytes long. If not given, a new one
3452 is instantiated.
3453
3454 Returns
3455 The PEM block, as a string.
3456
3457 PKCS#8
3458 PKCS#8 is a standard for storing and transferring private key informa‐
3459 tion. The wrapped key can either be clear or encrypted.
3460
3461 All encryption algorithms are based on passphrase-based key derivation.
3462 The following mechanisms are fully supported:
3463
3464 • PBKDF2WithHMAC-SHA1AndAES128-CBC
3465
3466 • PBKDF2WithHMAC-SHA1AndAES192-CBC
3467
3468 • PBKDF2WithHMAC-SHA1AndAES256-CBC
3469
3470 • PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC
3471
3472 • scryptAndAES128-CBC
3473
3474 • scryptAndAES192-CBC
3475
3476 • scryptAndAES256-CBC
3477
3478 The following mechanisms are only supported for importing keys. They
3479 are much weaker than the ones listed above, and they are provided for
3480 backward compatibility only:
3481
3482 • pbeWithMD5AndRC2-CBC
3483
3484 • pbeWithMD5AndDES-CBC
3485
3486 • pbeWithSHA1AndRC2-CBC
3487
3488 • pbeWithSHA1AndDES-CBC
3489
3490 Crypto.IO.PKCS8.unwrap(p8_private_key, passphrase=None)
3491 Unwrap a private key from a PKCS#8 blob (clear or encrypted).
3492
3493 Parameters
3494
3495 • p8_private_key (byte string) -- The private key wrapped
3496 into a PKCS#8 blob, DER encoded.
3497
3498 • passphrase (byte string or string) -- The passphrase to
3499 use to decrypt the blob (if it is encrypted).
3500
3501 Returns
3502 A tuple containing
3503
3504 1. the algorithm identifier of the wrapped key (OID,
3505 dotted string)
3506
3507 2. the private key (byte string, DER encoded)
3508
3509 3. the associated parameters (byte string, DER en‐
3510 coded) or None
3511
3512
3513 Raises ValueError -- if decoding fails
3514
3515 Crypto.IO.PKCS8.wrap(private_key, key_oid, passphrase=None, protec‐
3516 tion=None, prot_params=None, key_params=None, randfunc=None)
3517 Wrap a private key into a PKCS#8 blob (clear or encrypted).
3518
3519 Parameters
3520
3521 • private_key (byte string) -- The private key encoded in
3522 binary form. The actual encoding is algorithm specific.
3523 In most cases, it is DER.
3524
3525 • key_oid (string) -- The object identifier (OID) of the
3526 private key to wrap. It is a dotted string, like
3527 1.2.840.113549.1.1.1 (for RSA keys).
3528
3529 • passphrase (bytes string or string) -- The secret
3530 passphrase from which the wrapping key is derived. Set
3531 it only if encryption is required.
3532
3533 • protection (string) -- The identifier of the algorithm
3534 to use for securely wrapping the key. The default
3535 value is PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC.
3536
3537 • prot_params (dictionary) --
3538
3539 Parameters for the protection algorithm.
3540
3541 ┌────────────────┬────────────────────────────┐
3542 │Key │ Description │
3543 ├────────────────┼────────────────────────────┤
3544 │iteration_count │ The KDF algorithm is re‐ │
3545 │ │ peated several times to │
3546 │ │ slow down brute force at‐ │
3547 │ │ tacks on passwords (called │
3548 │ │ N or CPU/memory cost in │
3549 │ │ scrypt). The default │
3550 │ │ value for PBKDF2 is 1000. │
3551 │ │ The default value for │
3552 │ │ scrypt is 16384. │
3553 ├────────────────┼────────────────────────────┤
3554 │salt_size │ Salt is used to thwart │
3555 │ │ dictionary and rainbow at‐ │
3556 │ │ tacks on passwords. The │
3557 │ │ default value is 8 bytes. │
3558 ├────────────────┼────────────────────────────┤
3559 │block_size │ (scrypt only) Memory-cost │
3560 │ │ (r). The default value is │
3561 │ │ 8. │
3562 ├────────────────┼────────────────────────────┤
3563 │parallelization │ (scrypt only) CPU-cost │
3564 │ │ (p). The default value is │
3565 │ │ 1. │
3566 └────────────────┴────────────────────────────┘
3567
3568
3569 • key_params (DER object) -- The algorithm parameters as‐
3570 sociated to the private key. It is required for algo‐
3571 rithms like DSA, but not for others like RSA.
3572
3573 • randfunc (callable) -- Random number generation func‐
3574 tion; it should accept a single integer N and return a
3575 string of random data, N bytes long. If not specified,
3576 a new RNG will be instantiated from Crypto.Random.
3577
3578 Returns
3579 The PKCS#8-wrapped private key (possibly encrypted), as a
3580 byte string.
3581
3582 Crypto.Random package
3583 Crypto.Random.get_random_bytes(N)
3584 Return a random byte string of length N.
3585
3586 Crypto.Random.random module
3587 Crypto.Random.random.getrandbits(N)
3588 Return a random integer, at most N bits long.
3589
3590 Crypto.Random.random.randrange([start], stop[, step])
3591 Return a random integer in the range (start, stop, step). By
3592 default, start is 0 and step is 1.
3593
3594 Crypto.Random.random.randint(a, b)
3595 Return a random integer in the range no smaller than a and no
3596 larger than b.
3597
3598 Crypto.Random.random.choice(seq)
3599 Return a random element picked from the sequence seq.
3600
3601 Crypto.Random.random.shuffle(seq)
3602 Randomly shuffle the sequence seq in-place.
3603
3604 Crypto.Random.random.sample(population, k)
3605 Randomly chooses k distinct elements from the list population.
3606
3607 Crypto.Util package
3608 Useful modules that don't belong in any other package.
3609
3610 Crypto.Util.asn1 module
3611 This module provides minimal support for encoding and decoding ASN.1
3612 DER objects.
3613
3614 class Crypto.Util.asn1.DerBitString(value=b'', implicit=None, ex‐
3615 plicit=None)
3616 Class to model a DER BIT STRING.
3617
3618 An example of encoding is:
3619
3620 >>> from Crypto.Util.asn1 import DerBitString
3621 >>> from binascii import hexlify, unhexlify
3622 >>> bs_der = DerBitString(b'\xaa')
3623 >>> bs_der.value += b'\xbb'
3624 >>> print hexlify(bs_der.encode())
3625
3626 which will show 040300aabb, the DER encoding for the bit string
3627 b'\xAA\xBB'.
3628
3629 For decoding:
3630
3631 >>> s = unhexlify(b'040300aabb')
3632 >>> try:
3633 >>> bs_der = DerBitString()
3634 >>> bs_der.decode(s)
3635 >>> print hexlify(bs_der.value)
3636 >>> except ValueError:
3637 >>> print "Not a valid DER BIT STRING"
3638
3639 the output will be aabb.
3640
3641 Variables
3642 value (byte string) -- The content of the string
3643
3644 decode(der_encoded, strict=False)
3645 Decode a complete DER BIT STRING, and re-initializes this
3646 object with it.
3647
3648 Parameters
3649
3650 • der_encoded (byte string) -- a complete DER BIT
3651 STRING.
3652
3653 • strict (boolean) -- Whether decoding must check
3654 for strict DER compliancy.
3655
3656 Raises ValueError -- in case of parsing errors.
3657
3658 encode()
3659 Return the DER BIT STRING, fully encoded as a binary
3660 string.
3661
3662 class Crypto.Util.asn1.DerInteger(value=0, implicit=None, ex‐
3663 plicit=None)
3664 Class to model a DER INTEGER.
3665
3666 An example of encoding is:
3667
3668 >>> from Crypto.Util.asn1 import DerInteger
3669 >>> from binascii import hexlify, unhexlify
3670 >>> int_der = DerInteger(9)
3671 >>> print hexlify(int_der.encode())
3672
3673 which will show 020109, the DER encoding of 9.
3674
3675 And for decoding:
3676
3677 >>> s = unhexlify(b'020109')
3678 >>> try:
3679 >>> int_der = DerInteger()
3680 >>> int_der.decode(s)
3681 >>> print int_der.value
3682 >>> except ValueError:
3683 >>> print "Not a valid DER INTEGER"
3684
3685 the output will be 9.
3686
3687 Variables
3688 value (integer) -- The integer value
3689
3690 decode(der_encoded, strict=False)
3691 Decode a complete DER INTEGER DER, and re-initializes
3692 this object with it.
3693
3694 Parameters
3695 der_encoded (byte string) -- A complete INTEGER
3696 DER element.
3697
3698 Raises ValueError -- in case of parsing errors.
3699
3700 encode()
3701 Return the DER INTEGER, fully encoded as a binary string.
3702
3703 class Crypto.Util.asn1.DerNull
3704 Class to model a DER NULL element.
3705
3706 class Crypto.Util.asn1.DerObject(asn1Id=None, payload=b'', im‐
3707 plicit=None, constructed=False, explicit=None)
3708 Base class for defining a single DER object.
3709
3710 This class should never be directly instantiated.
3711
3712 decode(der_encoded, strict=False)
3713 Decode a complete DER element, and re-initializes this
3714 object with it.
3715
3716 Parameters
3717 der_encoded (byte string) -- A complete DER ele‐
3718 ment.
3719
3720 Raises ValueError -- in case of parsing errors.
3721
3722 encode()
3723 Return this DER element, fully encoded as a binary byte
3724 string.
3725
3726 class Crypto.Util.asn1.DerObjectId(value='', implicit=None, ex‐
3727 plicit=None)
3728 Class to model a DER OBJECT ID.
3729
3730 An example of encoding is:
3731
3732 >>> from Crypto.Util.asn1 import DerObjectId
3733 >>> from binascii import hexlify, unhexlify
3734 >>> oid_der = DerObjectId("1.2")
3735 >>> oid_der.value += ".840.113549.1.1.1"
3736 >>> print hexlify(oid_der.encode())
3737
3738 which will show 06092a864886f70d010101, the DER encoding for the
3739 RSA Object Identifier 1.2.840.113549.1.1.1.
3740
3741 For decoding:
3742
3743 >>> s = unhexlify(b'06092a864886f70d010101')
3744 >>> try:
3745 >>> oid_der = DerObjectId()
3746 >>> oid_der.decode(s)
3747 >>> print oid_der.value
3748 >>> except ValueError:
3749 >>> print "Not a valid DER OBJECT ID"
3750
3751 the output will be 1.2.840.113549.1.1.1.
3752
3753 Variables
3754 value (string) -- The Object ID (OID), a dot separated
3755 list of integers
3756
3757 decode(der_encoded, strict=False)
3758 Decode a complete DER OBJECT ID, and re-initializes this
3759 object with it.
3760
3761 Parameters
3762
3763 • der_encoded (byte string) -- A complete DER OB‐
3764 JECT ID.
3765
3766 • strict (boolean) -- Whether decoding must check
3767 for strict DER compliancy.
3768
3769 Raises ValueError -- in case of parsing errors.
3770
3771 encode()
3772 Return the DER OBJECT ID, fully encoded as a binary
3773 string.
3774
3775 class Crypto.Util.asn1.DerOctetString(value=b'', implicit=None)
3776 Class to model a DER OCTET STRING.
3777
3778 An example of encoding is:
3779
3780 >>> from Crypto.Util.asn1 import DerOctetString
3781 >>> from binascii import hexlify, unhexlify
3782 >>> os_der = DerOctetString(b'\xaa')
3783 >>> os_der.payload += b'\xbb'
3784 >>> print hexlify(os_der.encode())
3785
3786 which will show 0402aabb, the DER encoding for the byte string
3787 b'\xAA\xBB'.
3788
3789 For decoding:
3790
3791 >>> s = unhexlify(b'0402aabb')
3792 >>> try:
3793 >>> os_der = DerOctetString()
3794 >>> os_der.decode(s)
3795 >>> print hexlify(os_der.payload)
3796 >>> except ValueError:
3797 >>> print "Not a valid DER OCTET STRING"
3798
3799 the output will be aabb.
3800
3801 Variables
3802 payload (byte string) -- The content of the string
3803
3804 class Crypto.Util.asn1.DerSequence(startSeq=None, implicit=None)
3805 Class to model a DER SEQUENCE.
3806
3807 This object behaves like a dynamic Python sequence.
3808
3809 Sub-elements that are INTEGERs behave like Python integers.
3810
3811 Any other sub-element is a binary string encoded as a complete
3812 DER sub-element (TLV).
3813
3814 An example of encoding is:
3815
3816 >>> from Crypto.Util.asn1 import DerSequence, DerInteger
3817 >>> from binascii import hexlify, unhexlify
3818 >>> obj_der = unhexlify('070102')
3819 >>> seq_der = DerSequence([4])
3820 >>> seq_der.append(9)
3821 >>> seq_der.append(obj_der.encode())
3822 >>> print hexlify(seq_der.encode())
3823
3824 which will show 3009020104020109070102, the DER encoding of the
3825 sequence containing 4, 9, and the object with payload 02.
3826
3827 For decoding:
3828
3829 >>> s = unhexlify(b'3009020104020109070102')
3830 >>> try:
3831 >>> seq_der = DerSequence()
3832 >>> seq_der.decode(s)
3833 >>> print len(seq_der)
3834 >>> print seq_der[0]
3835 >>> print seq_der[:]
3836 >>> except ValueError:
3837 >>> print "Not a valid DER SEQUENCE"
3838
3839 the output will be:
3840
3841 3
3842 4
3843 [4, 9, b'.....']
3844
3845 decode(der_encoded, strict=False, nr_elements=None,
3846 only_ints_expected=False)
3847 Decode a complete DER SEQUENCE, and re-initializes this
3848 object with it.
3849
3850 Parameters
3851
3852 • der_encoded (byte string) -- A complete SEQUENCE
3853 DER element.
3854
3855 • nr_elements (None or integer or list of inte‐
3856 gers) -- The number of members the SEQUENCE can
3857 have
3858
3859 • only_ints_expected (boolean) -- Whether the SE‐
3860 QUENCE is expected to contain only integers.
3861
3862 • strict (boolean) -- Whether decoding must check
3863 for strict DER compliancy.
3864
3865 Raises ValueError -- in case of parsing errors.
3866
3867 DER INTEGERs are decoded into Python integers. Any other
3868 DER element is not decoded. Its validity is not checked.
3869
3870 encode()
3871 Return this DER SEQUENCE, fully encoded as a binary
3872 string.
3873
3874 Raises ValueError -- if some elements in the sequence are
3875 neither integers
3876 nor byte strings.
3877
3878 hasInts(only_non_negative=True)
3879 Return the number of items in this sequence that are in‐
3880 tegers.
3881
3882 Parameters
3883 only_non_negative (boolean) -- If True, negative
3884 integers are not counted in.
3885
3886 hasOnlyInts(only_non_negative=True)
3887 Return True if all items in this sequence are integers or
3888 non-negative integers.
3889
3890 This function returns False is the sequence is empty, or
3891 at least one member is not an integer.
3892
3893 Parameters
3894 only_non_negative (boolean) -- If True, the pres‐
3895 ence of negative integers causes the method to re‐
3896 turn False.
3897
3898 class Crypto.Util.asn1.DerSetOf(startSet=None, implicit=None)
3899 Class to model a DER SET OF.
3900
3901 An example of encoding is:
3902
3903 >>> from Crypto.Util.asn1 import DerBitString
3904 >>> from binascii import hexlify, unhexlify
3905 >>> so_der = DerSetOf([4,5])
3906 >>> so_der.add(6)
3907 >>> print hexlify(so_der.encode())
3908
3909 which will show 3109020104020105020106, the DER encoding of a
3910 SET OF with items 4,5, and 6.
3911
3912 For decoding:
3913
3914 >>> s = unhexlify(b'3109020104020105020106')
3915 >>> try:
3916 >>> so_der = DerSetOf()
3917 >>> so_der.decode(s)
3918 >>> print [x for x in so_der]
3919 >>> except ValueError:
3920 >>> print "Not a valid DER SET OF"
3921
3922 the output will be [4, 5, 6].
3923
3924 add(elem)
3925 Add an element to the set.
3926
3927 Parameters
3928 elem (byte string or integer) -- An element of the
3929 same type of objects already in the set. It can
3930 be an integer or a DER encoded object.
3931
3932 decode(der_encoded, strict=False)
3933 Decode a complete SET OF DER element, and re-initializes
3934 this object with it.
3935
3936 DER INTEGERs are decoded into Python integers. Any other
3937 DER element is left undecoded; its validity is not
3938 checked.
3939
3940 Parameters
3941
3942 • der_encoded (byte string) -- a complete DER BIT
3943 SET OF.
3944
3945 • strict (boolean) -- Whether decoding must check
3946 for strict DER compliancy.
3947
3948 Raises ValueError -- in case of parsing errors.
3949
3950 encode()
3951 Return this SET OF DER element, fully encoded as a binary
3952 string.
3953
3954 Crypto.Util.Padding module
3955 This module provides minimal support for adding and removing standard
3956 padding from data. Example:
3957
3958 >>> from Crypto.Util.Padding import pad, unpad
3959 >>> from Crypto.Cipher import AES
3960 >>> from Crypto.Random import get_random_bytes
3961 >>>
3962 >>> data = b'Unaligned' # 9 bytes
3963 >>> key = get_random_bytes(32)
3964 >>> iv = get_random_bytes(16)
3965 >>>
3966 >>> cipher1 = AES.new(key, AES.MODE_CBC, iv)
3967 >>> ct = cipher1.encrypt(pad(data, 16))
3968 >>>
3969 >>> cipher2 = AES.new(key, AES.MODE_CBC, iv)
3970 >>> pt = unpad(cipher2.decrypt(ct), 16)
3971 >>> assert(data == pt)
3972
3973 Crypto.Util.Padding.pad(data_to_pad, block_size, style='pkcs7')
3974 Apply standard padding.
3975
3976 Parameters
3977
3978 • data_to_pad (byte string) -- The data that needs to be
3979 padded.
3980
3981 • block_size (integer) -- The block boundary to use for
3982 padding. The output length is guaranteed to be a multi‐
3983 ple of block_size.
3984
3985 • style (string) -- Padding algorithm. It can be 'pkcs7'
3986 (default), 'iso7816' or 'x923'.
3987
3988 Returns
3989 the original data with the appropriate padding added at
3990 the end.
3991
3992 Return type
3993 byte string
3994
3995 Crypto.Util.Padding.unpad(padded_data, block_size, style='pkcs7')
3996 Remove standard padding.
3997
3998 Parameters
3999
4000 • padded_data (byte string) -- A piece of data with pad‐
4001 ding that needs to be stripped.
4002
4003 • block_size (integer) -- The block boundary to use for
4004 padding. The input length must be a multiple of
4005 block_size.
4006
4007 • style (string) -- Padding algorithm. It can be 'pkcs7'
4008 (default), 'iso7816' or 'x923'.
4009
4010 Returns
4011 data without padding.
4012
4013 Return type
4014 byte string
4015
4016 Raises ValueError -- if the padding is incorrect.
4017
4018 Crypto.Util.RFC1751 module
4019 Crypto.Util.RFC1751.english_to_key(s)
4020 Transform a string into a corresponding key.
4021
4022 Example:
4023
4024 >>> from Crypto.Util.RFC1751 import english_to_key
4025 >>> english_to_key('RAM LOIS GOAD CREW CARE HIT')
4026 b'66666666'
4027
4028 Parameters
4029 s (string) -- the string with the words separated by
4030 whitespace; the number of words must be a multiple of 6.
4031
4032 Returns
4033 A byte string.
4034
4035 Crypto.Util.RFC1751.key_to_english(key)
4036 Transform an arbitrary key into a string containing English
4037 words.
4038
4039 Example:
4040
4041 >>> from Crypto.Util.RFC1751 import key_to_english
4042 >>> key_to_english(b'66666666')
4043 'RAM LOIS GOAD CREW CARE HIT'
4044
4045 Parameters
4046 key (byte string) -- The key to convert. Its length must
4047 be a multiple of 8.
4048
4049 Returns
4050 A string of English words.
4051
4052 Crypto.Util.strxor module
4053 Fast XOR for byte strings.
4054
4055 Crypto.Util.strxor.strxor(term1, term2, output=None)
4056 XOR two byte strings.
4057
4058 Parameters
4059
4060 • term1 (bytes/bytearray/memoryview) -- The first term of
4061 the XOR operation.
4062
4063 • term2 (bytes/bytearray/memoryview) -- The second term
4064 of the XOR operation.
4065
4066 • output (bytearray/memoryview) -- The location where the
4067 result must be written to. If None, the result is re‐
4068 turned.
4069
4070 Return If output is None, a new bytes string with the result.
4071 Otherwise None.
4072
4073 Crypto.Util.strxor.strxor_c(term, c, output=None)
4074 XOR a byte string with a repeated sequence of characters.
4075
4076 Parameters
4077
4078 • term (bytes/bytearray/memoryview) -- The first term of
4079 the XOR operation.
4080
4081 • c (bytes) -- The byte that makes up the second term of
4082 the XOR operation.
4083
4084 • output (None or bytearray/memoryview) -- If not None,
4085 the location where the result is stored into.
4086
4087 Returns
4088 If output is None, a new bytes string with the result.
4089 Otherwise None.
4090
4091 Crypto.Util.Counter module
4092 Richer counter functions for CTR cipher mode.
4093
4094 CTR is a mode of operation for block ciphers.
4095
4096 The plaintext is broken up in blocks and each block is XOR-ed with a
4097 keystream to obtain the ciphertext. The keystream is produced by the
4098 encryption of a sequence of counter blocks, which all need to be dif‐
4099 ferent to avoid repetitions in the keystream. Counter blocks don't need
4100 to be secret.
4101
4102 The most straightforward approach is to include a counter field, and
4103 increment it by one within each subsequent counter block.
4104
4105 The new() function at the module level under Crypto.Cipher instantiates
4106 a new CTR cipher object for the relevant base algorithm. Its parame‐
4107 ters allow you define a counter block with a fixed structure:
4108
4109 • an optional, fixed prefix
4110
4111 • the counter field encoded in big endian mode
4112
4113 The length of the two components can vary, but together they must be as
4114 large as the block size (e.g. 16 bytes for AES).
4115
4116 Alternatively, the counter parameter can be used to pass a counter
4117 block object (created in advance with the function
4118 Crypto.Util.Counter.new()) for a more complex composition:
4119
4120 • an optional, fixed prefix
4121
4122 • the counter field, encoded in big endian or little endian mode
4123
4124 • an optional, fixed suffix
4125
4126 As before, the total length must match the block size.
4127
4128 The counter blocks with a big endian counter will look like this:
4129 [image]
4130
4131 The counter blocks with a little endian counter will look like this:
4132 [image]
4133
4134 Example of AES-CTR encryption with custom counter:
4135
4136 from Crypto.Cipher import AES
4137 from Crypto.Util import Counter
4138 from Crypto import Random
4139
4140 nonce = Random.get_random_bytes(4)
4141 ctr = Counter.new(64, prefix=nonce, suffix=b'ABCD', little_endian=True, initial_value=10)
4142 key = b'AES-128 symm key'
4143 plaintext = b'X'*1000000
4144 cipher = AES.new(key, AES.MODE_CTR, counter=ctr)
4145 ciphertext = cipher.encrypt(plaintext)
4146
4147 Crypto.Util.Counter.new(nbits, prefix=b'', suffix=b'', initial_value=1,
4148 little_endian=False, allow_wraparound=False)
4149 Create a stateful counter block function suitable for CTR en‐
4150 cryption modes.
4151
4152 Each call to the function returns the next counter block. Each
4153 counter block is made up by three parts:
4154
4155 ┌───────┬───────────────┬─────────┐
4156 │prefix │ counter value │ postfix │
4157 └───────┴───────────────┴─────────┘
4158
4159 The counter value is incremented by 1 at each call.
4160
4161 Parameters
4162
4163 • nbits (integer) -- Length of the desired counter value,
4164 in bits. It must be a multiple of 8.
4165
4166 • prefix (byte string) -- The constant prefix of the
4167 counter block. By default, no prefix is used.
4168
4169 • suffix (byte string) -- The constant postfix of the
4170 counter block. By default, no suffix is used.
4171
4172 • initial_value (integer) -- The initial value of the
4173 counter. Default value is 1. Its length in bits must
4174 not exceed the argument nbits.
4175
4176 • little_endian (boolean) -- If True, the counter number
4177 will be encoded in little endian format. If False (de‐
4178 fault), in big endian format.
4179
4180 • allow_wraparound (boolean) -- This parameter is ig‐
4181 nored.
4182
4183 Returns
4184 An object that can be passed with the counter parameter
4185 to a CTR mode cipher.
4186
4187 It must hold that len(prefix) + nbits//8 + len(suffix) matches
4188 the block size of the underlying block cipher.
4189
4190 Crypto.Util.number module
4191 Crypto.Util.number.GCD(x, y)
4192 Greatest Common Denominator of x and y.
4193
4194 Crypto.Util.number.bytes_to_long(s)
4195 Convert a byte string to a long integer (big endian).
4196
4197 In Python 3.2+, use the native method instead:
4198
4199 >>> int.from_bytes(s, 'big')
4200
4201 For instance:
4202
4203 >>> int.from_bytes(b'P', 'big')
4204 80
4205
4206 This is (essentially) the inverse of long_to_bytes().
4207
4208 Crypto.Util.number.ceil_div(n, d)
4209 Return ceil(n/d), that is, the smallest integer r such that r*d
4210 >= n
4211
4212 Crypto.Util.number.getPrime(N, randfunc=None)
4213 Return a random N-bit prime number.
4214
4215 N must be an integer larger than 1. If randfunc is omitted,
4216 then Random.get_random_bytes() is used.
4217
4218 Crypto.Util.number.getRandomInteger(N, randfunc=None)
4219 Return a random number at most N bits long.
4220
4221 If randfunc is omitted, then Random.get_random_bytes() is used.
4222
4223 Deprecated since version 3.0: This function is for internal use
4224 only and may be renamed or removed in the future. Use
4225 Crypto.Random.random.getrandbits() instead.
4226
4227
4228 Crypto.Util.number.getRandomNBitInteger(N, randfunc=None)
4229 Return a random number with exactly N-bits, i.e. a random number
4230 between 2**(N-1) and (2**N)-1.
4231
4232 If randfunc is omitted, then Random.get_random_bytes() is used.
4233
4234 Deprecated since version 3.0: This function is for internal use
4235 only and may be renamed or removed in the future.
4236
4237
4238 Crypto.Util.number.getRandomRange(a, b, randfunc=None)
4239 Return a random number n so that a <= n < b.
4240
4241 If randfunc is omitted, then Random.get_random_bytes() is used.
4242
4243 Deprecated since version 3.0: This function is for internal use
4244 only and may be renamed or removed in the future. Use
4245 Crypto.Random.random.randrange() instead.
4246
4247
4248 Crypto.Util.number.getStrongPrime(N, e=0, false_positive_prob=1e-06,
4249 randfunc=None)
4250 Return a random strong N-bit prime number. In this context, p
4251 is a strong prime if p-1 and p+1 have at least one large prime
4252 factor.
4253
4254 Parameters
4255
4256 • N (integer) -- the exact length of the strong prime.
4257 It must be a multiple of 128 and > 512.
4258
4259 • e (integer) -- if provided, the returned prime (minus
4260 1) will be coprime to e and thus suitable for RSA where
4261 e is the public exponent.
4262
4263 • false_positive_prob (float) -- The statistical proba‐
4264 bility for the result not to be actually a prime. It
4265 defaults to 10-6. Note that the real probability of a
4266 false-positive is far less. This is just the mathemati‐
4267 cally provable limit.
4268
4269 • randfunc (callable) -- A function that takes a parame‐
4270 ter N and that returns a random byte string of such
4271 length. If omitted, Crypto.Random.get_random_bytes()
4272 is used.
4273
4274 Returns
4275 The new strong prime.
4276
4277 Deprecated since version 3.0: This function is for internal use
4278 only and may be renamed or removed in the future.
4279
4280
4281 Crypto.Util.number.inverse(u, v)
4282 The inverse of u mod v.
4283
4284 Crypto.Util.number.isPrime(N, false_positive_prob=1e-06, randfunc=None)
4285 Test if a number N is a prime.
4286
4287 Parameters
4288
4289 • false_positive_prob (float) -- The statistical proba‐
4290 bility for the result not to be actually a prime. It
4291 defaults to 10-6. Note that the real probability of a
4292 false-positive is far less. This is just the mathemat‐
4293 ically provable limit.
4294
4295 • randfunc (callable) -- A function that takes a parame‐
4296 ter N and that returns a random byte string of such
4297 length. If omitted, Crypto.Random.get_random_bytes()
4298 is used.
4299
4300 Returns
4301 True is the input is indeed prime.
4302
4303 Crypto.Util.number.long_to_bytes(n, blocksize=0)
4304 Convert a positive integer to a byte string using big endian en‐
4305 coding.
4306
4307 If blocksize is absent or zero, the byte string will be of mini‐
4308 mal length.
4309
4310 Otherwise, the length of the byte string is guaranteed to be a
4311 multiple of blocksize. If necessary, zeroes (\x00) are added at
4312 the left.
4313
4314 NOTE:
4315 In Python 3, if you are sure that n can fit into blocksize
4316 bytes, you can simply use the native method instead:
4317
4318 >>> n.to_bytes(blocksize, 'big')
4319
4320 For instance:
4321
4322 >>> n = 80
4323 >>> n.to_bytes(2, 'big')
4324 b'\x00P'
4325
4326 However, and unlike this long_to_bytes() function, an Over‐
4327 flowError exception is raised if n does not fit.
4328
4329 Crypto.Util.number.size(N)
4330 Returns the size of the number N in bits.
4331
4332 All cryptographic functionalities are organized in sub-packages; each
4333 sub-package is dedicated to solving a specific class of problems.
4334
4335 ┌─────────────────┬────────────────────────────┐
4336 │Package │ Description │
4337 ├─────────────────┼────────────────────────────┤
4338 │Crypto.Cipher │ Modules for protecting │
4339 │ │ confidentiality that is, │
4340 │ │ for encrypting and de‐ │
4341 │ │ crypting data (example: │
4342 │ │ AES). │
4343 ├─────────────────┼────────────────────────────┤
4344 │Crypto.Signature │ Modules for assuring au‐ │
4345 │ │ thenticity, that is, for │
4346 │ │ creating and verifying │
4347 │ │ digital signatures of mes‐ │
4348 │ │ sages (example: PKCS#1 │
4349 │ │ v1.5). │
4350 ├─────────────────┼────────────────────────────┤
4351 │Crypto.Hash │ Modules for creating cryp‐ │
4352 │ │ tographic digests (exam‐ │
4353 │ │ ple: SHA-256). │
4354 ├─────────────────┼────────────────────────────┤
4355 │Crypto.PublicKey │ Modules for generating, │
4356 │ │ exporting or importing │
4357 │ │ public keys (example: RSA │
4358 │ │ or ECC). │
4359 ├─────────────────┼────────────────────────────┤
4360 │Crypto.Protocol │ Modules for faciliting se‐ │
4361 │ │ cure communications be‐ │
4362 │ │ tween parties, in most │
4363 │ │ cases by leveraging cryp‐ │
4364 │ │ tograpic primitives from │
4365 │ │ other modules (example: │
4366 │ │ Shamir's Secret Sharing │
4367 │ │ scheme). │
4368 ├─────────────────┼────────────────────────────┤
4369 │Crypto.IO │ Modules for dealing with │
4370 │ │ encodings commonly used │
4371 │ │ for cryptographic data │
4372 │ │ (example: PEM). │
4373 ├─────────────────┼────────────────────────────┤
4374 │Crypto.Random │ Modules for generating │
4375 │ │ random data. │
4376 └─────────────────┴────────────────────────────┘
4377
4378
4379 │Crypto.Util │ General purpose routines │
4380 │ │ (example: XOR for byte │
4381 │ │ strings). │
4382 └─────────────────┴────────────────────────────┘
4383
4384 In certain cases, there is some overlap between these categories. For
4385 instance, authenticity is also provided by Message Authentication
4386 Codes, and some can be built using digests, so they are included in the
4387 Crypto.Hash package (example: HMAC). Also, cryptographers have over
4388 time realized that encryption without authentication is often of lim‐
4389 ited value so recent ciphers found in the Crypto.Cipher package embed
4390 it (example: GCM).
4391
4392 PyCryptodome strives to maintain strong backward compatibility with the
4393 old PyCrypto's API (except for those few cases where that is harmful to
4394 security) so a few modules don't appear where they should (example: the
4395 ASN.1 module is under Crypto.Util as opposed to Crypto.IO).
4396
4398 Encrypt data with AES
4399 The following code generates a new AES128 key and encrypts a piece of
4400 data into a file. We use the EAX mode because it allows the receiver
4401 to detect any unauthorized modification (similarly, we could have used
4402 other authenticated encryption modes like GCM, CCM or SIV).
4403
4404 from Crypto.Cipher import AES
4405 from Crypto.Random import get_random_bytes
4406
4407 key = get_random_bytes(16)
4408 cipher = AES.new(key, AES.MODE_EAX)
4409 ciphertext, tag = cipher.encrypt_and_digest(data)
4410
4411 file_out = open("encrypted.bin", "wb")
4412 [ file_out.write(x) for x in (cipher.nonce, tag, ciphertext) ]
4413 file_out.close()
4414
4415 At the other end, the receiver can securely load the piece of data back
4416 (if they know the key!). Note that the code generates a ValueError ex‐
4417 ception when tampering is detected.
4418
4419 from Crypto.Cipher import AES
4420
4421 file_in = open("encrypted.bin", "rb")
4422 nonce, tag, ciphertext = [ file_in.read(x) for x in (16, 16, -1) ]
4423
4424 # let's assume that the key is somehow available again
4425 cipher = AES.new(key, AES.MODE_EAX, nonce)
4426 data = cipher.decrypt_and_verify(ciphertext, tag)
4427
4428 Generate an RSA key
4429 The following code generates a new RSA key pair (secret) and saves it
4430 into a file, protected by a password. We use the scrypt key derivation
4431 function to thwart dictionary attacks. At the end, the code prints our
4432 the RSA public key in ASCII/PEM format:
4433
4434 from Crypto.PublicKey import RSA
4435
4436 secret_code = "Unguessable"
4437 key = RSA.generate(2048)
4438 encrypted_key = key.export_key(passphrase=secret_code, pkcs=8,
4439 protection="scryptAndAES128-CBC")
4440
4441 file_out = open("rsa_key.bin", "wb")
4442 file_out.write(encrypted_key)
4443 file_out.close()
4444
4445 print(key.publickey().export_key())
4446
4447 The following code reads the private RSA key back in, and then prints
4448 again the public key:
4449
4450 from Crypto.PublicKey import RSA
4451
4452 secret_code = "Unguessable"
4453 encoded_key = open("rsa_key.bin", "rb").read()
4454 key = RSA.import_key(encoded_key, passphrase=secret_code)
4455
4456 print(key.publickey().export_key())
4457
4458 Generate public key and private key
4459 The following code generates public key stored in receiver.pem and pri‐
4460 vate key stored in private.pem. These files will be used in the exam‐
4461 ples below. Every time, it generates different public key and private
4462 key pair.
4463
4464 from Crypto.PublicKey import RSA
4465
4466 key = RSA.generate(2048)
4467 private_key = key.export_key()
4468 file_out = open("private.pem", "wb")
4469 file_out.write(private_key)
4470 file_out.close()
4471
4472 public_key = key.publickey().export_key()
4473 file_out = open("receiver.pem", "wb")
4474 file_out.write(public_key)
4475 file_out.close()
4476
4477 Encrypt data with RSA
4478 The following code encrypts a piece of data for a receiver we have the
4479 RSA public key of. The RSA public key is stored in a file called re‐
4480 ceiver.pem.
4481
4482 Since we want to be able to encrypt an arbitrary amount of data, we use
4483 a hybrid encryption scheme. We use RSA with PKCS#1 OAEP for asymmetric
4484 encryption of an AES session key. The session key can then be used to
4485 encrypt all the actual data.
4486
4487 As in the first example, we use the EAX mode to allow detection of
4488 unauthorized modifications.
4489
4490 from Crypto.PublicKey import RSA
4491 from Crypto.Random import get_random_bytes
4492 from Crypto.Cipher import AES, PKCS1_OAEP
4493
4494 data = "I met aliens in UFO. Here is the map.".encode("utf-8")
4495 file_out = open("encrypted_data.bin", "wb")
4496
4497 recipient_key = RSA.import_key(open("receiver.pem").read())
4498 session_key = get_random_bytes(16)
4499
4500 # Encrypt the session key with the public RSA key
4501 cipher_rsa = PKCS1_OAEP.new(recipient_key)
4502 enc_session_key = cipher_rsa.encrypt(session_key)
4503
4504 # Encrypt the data with the AES session key
4505 cipher_aes = AES.new(session_key, AES.MODE_EAX)
4506 ciphertext, tag = cipher_aes.encrypt_and_digest(data)
4507 [ file_out.write(x) for x in (enc_session_key, cipher_aes.nonce, tag, ciphertext) ]
4508 file_out.close()
4509
4510 The receiver has the private RSA key. They will use it to decrypt the
4511 session key first, and with that the rest of the file:
4512
4513 from Crypto.PublicKey import RSA
4514 from Crypto.Cipher import AES, PKCS1_OAEP
4515
4516 file_in = open("encrypted_data.bin", "rb")
4517
4518 private_key = RSA.import_key(open("private.pem").read())
4519
4520 enc_session_key, nonce, tag, ciphertext = \
4521 [ file_in.read(x) for x in (private_key.size_in_bytes(), 16, 16, -1) ]
4522
4523 # Decrypt the session key with the private RSA key
4524 cipher_rsa = PKCS1_OAEP.new(private_key)
4525 session_key = cipher_rsa.decrypt(enc_session_key)
4526
4527 # Decrypt the data with the AES session key
4528 cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce)
4529 data = cipher_aes.decrypt_and_verify(ciphertext, tag)
4530 print(data.decode("utf-8"))
4531
4533 Is CTR cipher mode compatible with Java?
4534 Yes. When you instantiate your AES cipher in Java:
4535
4536 Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
4537
4538 SecretKeySpec keySpec = new SecretKeySpec(new byte[16], "AES");
4539 IvParameterSpec ivSpec = new IvParameterSpec(new byte[16]);
4540
4541 cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
4542
4543 You are effectively using ctr_mode without a fixed nonce and with a
4544 128-bit big endian counter starting at 0. The counter will wrap around
4545 only after 2¹²⁸ blocks.
4546
4547 You can replicate the same keystream in PyCryptodome with:
4548
4549 ivSpec = b'\x00' * 16
4550 ctr = AES.new(keySpec, AES.MODE_CTR, initial_value=ivSpec, nonce=b'')
4551
4552 Are RSASSA-PSS signatures compatible with Java or OpenSSL?
4553 Yes. For Java, you must consider that by default the mask is generated
4554 by MGF1 with SHA-1 (regardless of how you hash the message) and the
4555 salt is 20 bytes long.
4556
4557 If you want to use another algorithm or another salt length, you must
4558 instantiate a PSSParameterSpec object, for instance:
4559
4560 Signature ss = Signature.getInstance("SHA256withRSA/PSS");
4561 AlgorithmParameters pss1 = ss.getParameters();
4562 PSSParameterSpec pssParameterSpec = new PSSParameterSpec("SHA-256", "MGF1", new MGF1ParameterSpec("SHA-256"), 32, 0xBC);
4563 ss.setParameter(spec1);
4564
4565 On the other hand, a quirk of OpenSSL (and of a few other libraries,
4566 especially if they are wrappers to OpenSSL) is that the default salt
4567 length is maximized, and it does not match in size the digest applied
4568 to the message, as recommended in RFC8017. In PyCryptodome, you maxi‐
4569 mize the salt length with:
4570
4571 key = RSA.import_key(open('privkey.der').read())
4572 h = SHA256.new(message)
4573 salt_bytes = key.size_in_bytes() - h.digest_size - 2
4574 signature = pss.new(key, salt_bytes=salt_bytes).sign(h)
4575
4576 Why do I get the error No module named Crypto on Windows?
4577 Check the directory where Python packages are installed, like:
4578
4579 /path/to/python/Lib/site-packages/
4580
4581 You might find a directory named crypto, with all the PyCryptodome
4582 files in it.
4583
4584 The most likely cause is described here and you can fix the problem
4585 with:
4586
4587 pip uninstall crypto
4588 pip uninstall pycryptodome
4589 pip install pycryptodome
4590
4591 The root cause is that, in the past, you most likely have installed an
4592 unrelated but similarly named package called crypto, which happens to
4593 operate under the namespace crypto.
4594
4595 The Windows filesystem is case-insensitive so crypto and Crypto are ef‐
4596 fectively considered the same thing. When you subsequently install py‐
4597 cryptodome, pip finds that a directory named with the target namespace
4598 already exists (under the rules of the underlying filesystem), and
4599 therefore installs all the sub-packages of pycryptodome in it. This is
4600 probably a reasonable behavior, if it wasn't that pip does not issue
4601 any warning even if it could detect the issue.
4602
4603 Why does strxor raise TypeError: argument 2 must be bytes, not bytearray?
4604 Most probably you have installed both the pycryptodome and the old py‐
4605 crypto packages.
4606
4607 Run pip uninstall pycrypto and try again.
4608
4609 The old PyCrypto shipped with a strxor module written as a native li‐
4610 brary (.so or .dll file). If you install pycryptodome, the old native
4611 module will still take priority over the new Python extension that
4612 comes in the latter.
4613
4615 • Do not be afraid to contribute with small and apparently insignifi‐
4616 cant improvements like correction to typos. Every change counts.
4617
4618 • Read carefully the license of PyCryptodome. By submitting your code,
4619 you acknowledge that you accept to release it according to the BSD
4620 2-clause license.
4621
4622 • You must disclaim which parts of your code in your contribution were
4623 partially copied or derived from an existing source. Ensure that the
4624 original is licensed in a way compatible to the BSD 2-clause license.
4625
4626 • You can propose changes in any way you find most convenient. How‐
4627 ever, the preferred approach is to:
4628
4629 • Clone the main repository on GitHub.
4630
4631 • Create a branch and modify the code.
4632
4633 • Send a pull request upstream with a meaningful description.
4634
4635 • Provide tests (in Crypto.SelfTest) along with code. If you fix a bug
4636 add a test that fails in the current version and passes with your
4637 change.
4638
4639 • If your change breaks backward compatibility, highlight it and in‐
4640 clude a justification.
4641
4642 • Ensure that your code complies to PEP8 and PEP257.
4643
4644 • If you add or modify a public interface, make sure the relevant type
4645 stubs remain up to date.
4646
4647 • Ensure that your code does not use constructs or includes modules not
4648 present in Python 2.6.
4649
4650 • Add a short summary of the change to the file Changelog.rst.
4651
4652 • Add your name to the list of contributors in the file AUTHORS.rst.
4653
4654 The PyCryptodome mailing list is hosted on Google Groups. You can mail
4655 any comment or question to pycryptodome@googlegroups.com.
4656
4657 Bug reports can be filed on the GitHub tracker.
4658
4660 Future releases will include:
4661
4662 • Update Crypto.Signature.DSS to FIPS 186-4
4663
4664 • Make all hash objects non-copyable and immutable after the first di‐
4665 gest
4666
4667 • Add alias 'segment_bits' to parameter 'segment_size' for CFB
4668
4669 • Coverage testing
4670
4671 • Implement AES with bitslicing
4672
4673 • Add unit tests for PEM I/O
4674
4675 • Move old ciphers into a Museum submodule
4676
4677 • Add more ECC curves
4678
4679 • Import/export of ECC keys with compressed points
4680
4681 •
4682
4683 Add algorithms:
4684
4685 • Elliptic Curves (ECIES, ECDH)
4686
4687 • Camellia, GOST
4688
4689 • Diffie-Hellman
4690
4691 • bcrypt
4692
4693 • argon2
4694
4695 • SRP
4696
4697 •
4698
4699 Add more key management:
4700
4701 • Export/import of DSA domain parameters
4702
4703 • JWK
4704
4705 • Add support for CMS/PKCS#7
4706
4707 • Add support for RNG backed by PKCS#11 and/or KMIP
4708
4709 • Add support for Format-Preserving Encryption
4710
4711 • Remove dependency on libtomcrypto headers
4712
4713 • Speed up (T)DES with a bitsliced implementation
4714
4715 • Run lint on the C code
4716
4717 • Add (minimal) support for PGP
4718
4719 • Add (minimal) support for PKIX / X.509
4720
4722 3.11.0 (8 October 2021)
4723 Resolved issues
4724 • GH#512: Especially for very small bit sizes, Crypto.Util.number.get‐
4725 Prime() was occasionally generating primes larger than given the bit
4726 size. Thanks to Koki Takahashi.
4727
4728 • GH#552: Correct typing annotations for PKCS115_Cipher.decrypt().
4729
4730 • GH#555: decrypt() method of a PKCS#1v1.5 cipher returned a bytearray
4731 instead of bytes.
4732
4733 • GH#557: External DSA domain parameters were accepted even when the
4734 modulus (p) was not prime. This affected Crypto.PublicKey.DSA.gener‐
4735 ate() and Crypto.PublicKey.DSA.construct(). Thanks to Koki Taka‐
4736 hashi.
4737
4738 New features
4739 • Added cSHAKE128 and cSHAKE256 (of SHA-3 family). Thanks to Michael
4740 Schaffner.
4741
4742 • GH#558: The flag RTLD_DEEPBIND passed to dlopen() is not well sup‐
4743 ported by address sanitizers. It is now possible to set the environ‐
4744 ment variable PYCRYPTDOME_DISABLE_DEEPBIND to drop that flag and al‐
4745 low security testing.
4746
4747 3.10.4 (25 September 2021)
4748 Resolved issues
4749 • Output of Crypto.Util.number.long_to_bytes() was not always a multi‐
4750 ple of blocksize.
4751
4752 3.10.3 (22 September 2021)
4753 Resolved issues
4754 • GH#376: Fixed symbol conflict between different versions of libgmp.
4755
4756 • GH#481: Improved robustness of PKCS#1v1.5 decryption against timing
4757 attacks.
4758
4759 • GH#506 and GH#509: Fixed segmentation faults on Apple M1 and other
4760 Aarch64 SoCs, when the GMP library add accessed via ctypes. Do not
4761 use GMP's own sscanf and snprintf routines: instead, use simpler con‐
4762 version routines.
4763
4764 • GH#510: Workaround for cffi calling ctypes.util.find_library(), which
4765 invokes gcc and ld on Linux, considerably slowing down all imports.
4766 On certain configurations, that may also leave temporary files be‐
4767 hind.
4768
4769 • GH#517: Fix RSAES-OAEP, as it didn't always fail when zero padding
4770 was incorrect.
4771
4772 New features
4773 • Added support for SHA-3 hash functions to HMAC.
4774
4775 Other changes
4776 • The Windows wheels of Python 2.7 now require the VS2015 runtime to be
4777 installed in the system, because Microsoft stopped distributing the
4778 VS2008 compiler in April 2021. VS2008 was used to compile the Python
4779 2.7 extensions.
4780
4781 3.10.1 (9 February 2021)
4782 Other changes
4783 • Python 3 wheels use abi3 ABI tag.
4784
4785 • Remove Appveyor CI.
4786
4787 3.10.0 (6 February 2021)
4788 Resolved issues
4789 • Fixed a potential memory leak when initializing block ciphers.
4790
4791 • GH#466: Crypto.Math.miller_rabin_test() was still using the system
4792 random source and not the one provided as parameter.
4793
4794 • GH#469: RSA objects have the method public_key() like ECC objects.
4795 The old method publickey() is still available for backward compati‐
4796 bility.
4797
4798 • GH#476: Crypto.Util.Padding.unpad() was raising an incorrect excep‐
4799 tion in case of zero-length inputs. Thanks to Captainowie.
4800
4801 • GH#491: better exception message when Counter.new() is called with an
4802 integer initial_value than doesn't fit into nbits bits.
4803
4804 • GH#496: added missing block_size member for ECB cipher objects.
4805 Thanks to willem.
4806
4807 • GH#500: nonce member of an XChaCha20 cipher object was not matching
4808 the original nonce. Thanks to Charles Machalow.
4809
4810 Other changes
4811 • The bulk of the test vectors have been moved to the separate package
4812 pycryptodome-test-vectors. As result, packages pycryptodome and py‐
4813 cryptodomex become significantly smaller (from 14MB to 3MB).
4814
4815 • Moved CI tests and build service from Travis CI to GitHub Actions.
4816
4817 Breaks in compatibility
4818 • Drop support for Python 2.6 and 3.4.
4819
4820 3.9.9 (2 November 2020)
4821 Resolved issues
4822 • GH#435: Fixed Crypto.Util.number.size for negative numbers.
4823
4824 New features
4825 • Build Python 3.9 wheels on Windows.
4826
4827 3.9.8 (23 June 2020)
4828 Resolved issues
4829 • GH#426: The Shamir's secret sharing implementation is not actually
4830 compatible with ssss. Added an optional parameter to enable interop‐
4831 erability.
4832
4833 • GH#427: Skip altogether loading of gmp.dll on Windows.
4834
4835 • GH#420: Fix incorrect CFB decryption when the input and the output
4836 are the same buffer.
4837
4838 New features
4839 • Speed up Shamir's secret sharing routines. Thanks to ncarve.
4840
4841 3.9.7 (20 February 2020)
4842 Resolved issues
4843 • GH#381: Make notarization possible again on OS X when using wheels.
4844 Thanks to Colin Atkinson.
4845
4846 3.9.6 (2 February 2020)
4847 Resolved issues
4848 • Fix building of wheels for OS X by explicitly setting sysroot loca‐
4849 tion.
4850
4851 3.9.5 (1 February 2020)
4852 Resolved issues
4853 • RSA OAEP decryption was not verifying that all PS bytes are zero.
4854
4855 • GH#372: fixed memory leak for operations that use memoryviews when
4856 cffi is not installed.
4857
4858 • Fixed wrong ASN.1 OID for HMAC-SHA512 in PBE2.
4859
4860 New features
4861 • Updated Wycheproof test vectors to version 0.8r12.
4862
4863 3.9.4 (18 November 2019)
4864 Resolved issues
4865 • GH#341: Prevent key_to_english from creating invalid data when fed
4866 with keys of length not multiple of 8. Thanks to vstoykovbg.
4867
4868 • GH#347: Fix blocking RSA signing/decryption when key has very small
4869 factor. Thanks to Martijn Pieters.
4870
4871 3.9.3 (12 November 2019)
4872 Resolved issues
4873 • GH#308: Align stack of functions using SSE2 intrinsics to avoid
4874 crashes, when compiled with gcc on 32-bit x86 platforms.
4875
4876 3.9.2 (10 November 2019)
4877 New features
4878 • Add Python 3.8 wheels for Mac.
4879
4880 Resolved issues
4881 • GH#308: Avoid allocating arrays of __m128i on the stack, to cope with
4882 buggy compilers.
4883
4884 • GH#322: Remove blanket -O3 optimization for gcc and clang, to cope
4885 with buggy compilers.
4886
4887 • GH#337: Fix typing stubs for signatures.
4888
4889 • GH#338: Deal with gcc installations that don't have x86intrin.h.
4890
4891 3.9.1 (1 November 2019)
4892 New features
4893 • Add Python 3.8 wheels for Linux and Windows.
4894
4895 Resolved issues
4896 • GH#328: minor speed-up when importing RSA.
4897
4898 3.9.0 (27 August 2019)
4899 New features
4900 • Add support for loading PEM files encrypted with AES256-CBC.
4901
4902 • Add support for XChaCha20 and XChaCha20-Poly1305 ciphers.
4903
4904 • Add support for bcrypt key derivation function (Crypto.Proto‐
4905 col.KDF.bcrypt).
4906
4907 • Add support for left multiplication of an EC point by a scalar.
4908
4909 • Add support for importing ECC and RSA keys in the new OpenSSH format.
4910
4911 Resolved issues
4912 • GH#312: it was not possible to invert an EC point anymore.
4913
4914 • GH#316: fix printing of DSA keys.
4915
4916 • GH#317: DSA.generate() was not always using the randfunc input.
4917
4918 • GH#285: the MD2 hash had block size of 64 bytes instead of 16; as re‐
4919 sult the HMAC construction gave incorrect results.
4920
4921 3.8.2 (30 May 2019)
4922 Resolved issues
4923 • GH#291: fix strict aliasing problem, emerged with GCC 9.1.
4924
4925 3.8.1 (4 April 2019)
4926 New features
4927 • Add support for loading PEM files encrypted with AES192-CBC and
4928 AES256-GCM.
4929
4930 • When importing ECC keys in PEM format, ignore the redundant EC PARAMS
4931 section that was included by certain openssl commands.
4932
4933 Resolved issues
4934 • repr() did not work for ECC.EccKey objects.
4935
4936 • Fix installation in development mode (setup install develop or pip
4937 install -e .).
4938
4939 • Minimal length for Blowfish cipher is 32 bits, not 40 bits.
4940
4941 • Various updates to docs.
4942
4943 3.8.0 (23 March 2019)
4944 New features
4945 • Speed-up ECC performance. ECDSA is 33 times faster on the NIST P-256
4946 curve.
4947
4948 • Added support for NIST P-384 and P-521 curves.
4949
4950 • EccKey has new methods size_in_bits() and size_in_bytes().
4951
4952 • Support HMAC-SHA224, HMAC-SHA256, HMAC-SHA384, and HMAC-SHA512 in
4953 PBE2/PBKDF2.
4954
4955 Resolved issues
4956 • DER objects were not rejected if their length field had a leading
4957 zero.
4958
4959 • Allow legacy RC2 ciphers to have 40-bit keys.
4960
4961 • ASN.1 Object IDs did not allow the value 0 in the path.
4962
4963 Breaks in compatibility
4964 • point_at_infinity() becomes an instance method for Crypto.Pub‐
4965 licKey.ECC.EccKey, from a static one.
4966
4967 3.7.3 (19 January 2019)
4968 Resolved issues
4969 • GH#258: False positive on PSS signatures when externally provided
4970 salt is too long.
4971
4972 • Include type stub files for Crypto.IO and Crypto.Util.
4973
4974 3.7.2 (26 November 2018)
4975 Resolved issues
4976 • GH#242: Fixed compilation problem on ARM platforms.
4977
4978 3.7.1 (25 November 2018)
4979 New features
4980 • Added type stubs to enable static type checking with mypy. Thanks to
4981 Michael Nix.
4982
4983 • New update_after_digest flag for CMAC.
4984
4985 Resolved issues
4986 • GH#232: Fixed problem with gcc 4.x when compiling ghash_clmul.c.
4987
4988 • GH#238: Incorrect digest value produced by CMAC after cloning the ob‐
4989 ject.
4990
4991 • Method update() of an EAX cipher object was returning the underlying
4992 CMAC object, instead of the EAX object itself.
4993
4994 • Method update() of a CMAC object was not throwing an exception after
4995 the digest was computed (with digest() or verify()).
4996
4997 3.7.0 (27 October 2018)
4998 New features
4999 • Added support for Poly1305 MAC (with AES and ChaCha20 ciphers for key
5000 derivation).
5001
5002 • Added support for ChaCha20-Poly1305 AEAD cipher.
5003
5004 • New parameter output for Crypto.Util.strxor.strxor,
5005 Crypto.Util.strxor.strxor_c, encrypt and decrypt methods in symmetric
5006 ciphers (Crypto.Cipher package). output is a pre-allocated buffer (a
5007 bytearray or a writeable memoryview) where the result must be stored.
5008 This requires less memory for very large payloads; it is also more
5009 efficient when encrypting (or decrypting) several small payloads.
5010
5011 Resolved issues
5012 • GH#266: AES-GCM hangs when processing more than 4GB at a time on x86
5013 with PCLMULQDQ instruction.
5014
5015 Breaks in compatibility
5016 • Drop support for Python 3.3.
5017
5018 • Remove Crypto.Util.py3compat.unhexlify and Crypto.Util.py3com‐
5019 pat.hexlify.
5020
5021 • With the old Python 2.6, use only ctypes (and not cffi) to interface
5022 to native code.
5023
5024 3.6.6 (17 August 2018)
5025 Resolved issues
5026 • GH#198: Fix vulnerability on AESNI ECB with payloads smaller than 16
5027 bytes (CVE-2018-15560).
5028
5029 3.6.5 (12 August 2018)
5030 Resolved issues
5031 • GH#187: Fixed incorrect AES encryption/decryption with AES accelera‐
5032 tion on x86 due to gcc's optimization and strict aliasing rules.
5033
5034 • GH#188: More prime number candidates than necessary where discarded
5035 as composite due to the limited way D values were searched in the
5036 Lucas test.
5037
5038 • Fixed ResouceWarnings and DeprecationWarnings.
5039
5040 • Workaround for Python 3.7.0 bug on Windows (‐
5041 https://bugs.python.org/issue34108).
5042
5043 3.6.4 (10 July 2018)
5044 New features
5045 • Build Python 3.7 wheels on Linux, Windows and Mac.
5046
5047 Resolved issues
5048 • GH#178: Rename _cpuid module to make upgrades more robust.
5049
5050 • More meaningful exceptions in case of mismatch in IV length
5051 (CBC/OFB/CFB modes).
5052
5053 • Fix compilation issues on Solaris 10/11.
5054
5055 3.6.3 (21 June 2018)
5056 Resolved issues
5057 • GH#175: Fixed incorrect results for CTR encryption/decryption with
5058 more than 8 blocks.
5059
5060 3.6.2 (19 June 2018)
5061 New features
5062 • ChaCha20 accepts 96 bit nonces (in addition to 64 bit nonces) as de‐
5063 fined in RFC7539.
5064
5065 • Accelerate AES-GCM on x86 using PCLMULQDQ instruction.
5066
5067 • Accelerate AES-ECB and AES-CTR on x86 by pipelining AESNI instruc‐
5068 tions.
5069
5070 • As result of the two improvements above, on x86 (Broadwell):
5071
5072 • AES-ECB and AES-CTR are 3x faster
5073
5074 • AES-GCM is 9x faster
5075
5076 Resolved issues
5077 • On Windows, MPIR library was stilled pulled in if renamed to gmp.dll.
5078
5079 Breaks in compatibility
5080 • In Crypto.Util.number, functions floor_div and exact_div have been
5081 removed. Also, ceil_div is limited to non-negative terms only.
5082
5083 3.6.1 (15 April 2018)
5084 New features
5085 • Added Google Wycheproof tests (https://github.com/google/wycheproof)
5086 for RSA, DSA, ECDSA, GCM, SIV, EAX, CMAC.
5087
5088 • New parameter mac_len (length of MAC tag) for CMAC.
5089
5090 Resolved issues
5091 • In certain circumstances (at counter wrapping, which happens on aver‐
5092 age after 32 GB) AES GCM produced wrong ciphertexts.
5093
5094 • Method encrypt() of AES SIV cipher could be still called, whereas
5095 only encrypt_and_digest() is allowed.
5096
5097 3.6.0 (8 April 2018)
5098 New features
5099 • Introduced export_key and deprecated exportKey for DSA and RSA key
5100 objects.
5101
5102 • Ciphers and hash functions accept memoryview objects in input.
5103
5104 • Added support for SHA-512/224 and SHA-512/256.
5105
5106 Resolved issues
5107 • Reintroduced Crypto.__version__ variable as in PyCrypto.
5108
5109 • Fixed compilation problem with MinGW.
5110
5111 3.5.1 (8 March 2018)
5112 Resolved issues
5113 • GH#142. Fix mismatch with declaration and definition of addmul128.
5114
5115 3.5.0 (7 March 2018)
5116 New features
5117 • Import and export of ECC curves in compressed form.
5118
5119 • The initial counter for a cipher in CTR mode can be a byte string (in
5120 addition to an integer).
5121
5122 • Faster PBKDF2 for HMAC-based PRFs (at least 20x for short passwords,
5123 more for longer passwords). Thanks to Christian Heimes for pointing
5124 out the implementation was under-optimized.
5125
5126 • The salt for PBKDF2 can be either a string or bytes (GH#67).
5127
5128 • Ciphers and hash functions accept data as bytearray, not just binary
5129 strings.
5130
5131 • The old SHA-1 and MD5 hash functions are available even when Python's
5132 own hashlib does not include them.
5133
5134 Resolved issues
5135 • Without libgmp, modular exponentiation (since v3.4.8) crashed on
5136 32-bit big-endian systems.
5137
5138 Breaks in compatibility
5139 • Removed support for Python < 2.6.
5140
5141 3.4.12 (5 February 2018)
5142 Resolved issues
5143 • GH#129. pycryptodomex could only be installed via wheels.
5144
5145 3.4.11 (5 February 2018)
5146 Resolved issues
5147 • GH#121. the record list was still not correct due to PEP3147 and
5148 __pycache__ directories. Thanks again to John O'Brien.
5149
5150 3.4.10 (2 February 2018)
5151 Resolved issues
5152 • When creating ElGamal keys, the generator wasn't a square residue:
5153 ElGamal encryption done with those keys cannot be secure under the
5154 DDH assumption. Thanks to Weikeng Chen.
5155
5156 3.4.9 (1 February 2018)
5157 New features
5158 • More meaningful error messages while importing an ECC key.
5159
5160 Resolved issues
5161 • GH#123 and #125. The SSE2 command line switch was not always passed
5162 on 32-bit x86 platforms.
5163
5164 • GH#121. The record list (--record) was not always correctly filled
5165 for the pycryptodomex package. Thanks to John W. O'Brien.
5166
5167 3.4.8 (27 January 2018)
5168 New features
5169 • Added a native extension in pure C for modular exponentiation, opti‐
5170 mized for SSE2 on x86. In the process, we drop support for the arbi‐
5171 trary arithmetic library MPIR on Windows, which is painful to compile
5172 and deploy. The custom modular exponentiation is 130% (160%) slower
5173 on an Intel CPU in 32-bit (64-bit) mode, compared to MPIR. Still,
5174 that is much faster that CPython's own pow() function which is 900%
5175 (855%) slower than MPIR. Support for the GMP library on Unix remains.
5176
5177 • Added support for manylinux wheels.
5178
5179 • Support for Python 3.7.
5180
5181 Resolved issues
5182 • The DSA parameter 'p' prime was created with 255 bits cleared (but
5183 still with the correct strength).
5184
5185 • GH#106. Not all docs were included in the tar ball. Thanks to
5186 Christopher Hoskin.
5187
5188 • GH#109. ECDSA verification failed for DER encoded signatures. Thanks
5189 to Alastair Houghton.
5190
5191 • Human-friendly messages for padding errors with ECB and CBC.
5192
5193 3.4.7 (26 August 2017)
5194 New features
5195 • API documentation is made with sphinx instead of epydoc.
5196
5197 • Start using importlib instead of imp where available.
5198
5199 Resolved issues
5200 • GH#82. Fixed PEM header for RSA/DSA public keys.
5201
5202 3.4.6 (18 May 2017)
5203 Resolved issues
5204 • GH#65. Keccak, SHA3, SHAKE and the seek functionality for ChaCha20
5205 were not working on big endian machines. Fixed. Thanks to Mike
5206 Gilbert.
5207
5208 • A few fixes in the documentation.
5209
5210 3.4.5 (6 February 2017)
5211 Resolved issues
5212 • The library can also be compiled using MinGW.
5213
5214 3.4.4 (1 February 2017)
5215 Resolved issues
5216 • Removed use of alloca().
5217
5218 • [Security] Removed implementation of deprecated "quick check" feature
5219 of PGP block cipher mode.
5220
5221 • Improved the performance of scrypt by converting some Python to C.
5222
5223 3.4.3 (17 October 2016)
5224 Resolved issues
5225 • Undefined warning was raised with libgmp version < 5
5226
5227 • Forgot inclusion of alloca.h
5228
5229 • Fixed a warning about type mismatch raised by recent versions of cffi
5230
5231 3.4.2 (8 March 2016)
5232 Resolved issues
5233 • Fix renaming of package for install command.
5234
5235 3.4.1 (21 February 2016)
5236 New features
5237 • Added option to install the library under the Cryptodome package (in‐
5238 stead of Crypto).
5239
5240 3.4 (7 February 2016)
5241 New features
5242 • Added Crypto.PublicKey.ECC module (NIST P-256 curve only), including
5243 export/import of ECC keys.
5244
5245 • Added support for ECDSA (FIPS 186-3 and RFC6979).
5246
5247 • For CBC/CFB/OFB/CTR cipher objects, encrypt() and decrypt() cannot be
5248 intermixed.
5249
5250 • CBC/CFB/OFB, the cipher objects have both IV and iv attributes.
5251 new() accepts IV as well as iv as parameter.
5252
5253 • For CFB/OPENPGP cipher object, encrypt() and decrypt() do not require
5254 the plaintext or ciphertext pieces to have length multiple of the CFB
5255 segment size.
5256
5257 • Added dedicated tests for all cipher modes, including NIST test vec‐
5258 tors
5259
5260 • CTR/CCM/EAX/GCM/SIV/Salsa20/ChaCha20 objects expose the nonce attri‐
5261 bute.
5262
5263 • For performance reasons, CCM cipher optionally accepted a pre-decla‐
5264 ration of the length of the associated data, but never checked if the
5265 actual data passed to the cipher really matched that length. Such
5266 check is now enforced.
5267
5268 • CTR cipher objects accept parameter nonce and possibly initial_value
5269 in alternative to counter (which is deprecated).
5270
5271 • All iv/IV and nonce parameters are optional. If not provided, they
5272 will be randomly generated (exception: nonce for CTR mode in case of
5273 block sizes smaller than 16 bytes).
5274
5275 • Refactored ARC2 cipher.
5276
5277 • Added Crypto.Cipher.DES3.adjust_key_parity() function.
5278
5279 • Added RSA.import_key as an alias to the deprecated RSA.importKey
5280 (same for the DSA module).
5281
5282 • Added size_in_bits() and size_in_bytes() methods to RsaKey.
5283
5284 Resolved issues
5285 • RSA key size is now returned correctly in RsaKey.__repr__() method
5286 (kudos to hannesv).
5287
5288 • CTR mode does not modify anymore counter parameter passed to new()
5289 method.
5290
5291 • CTR raises OverflowError instead of ValueError when the counter wraps
5292 around.
5293
5294 • PEM files with Windows newlines could not be imported.
5295
5296 • Crypto.IO.PEM and Crypto.IO.PKCS8 used to accept empty passphrases.
5297
5298 • GH#6: NotImplementedError now raised for unsupported methods sign,
5299 verify, encrypt, decrypt, blind, unblind and size in objects RsaKey,
5300 DsaKey, ElGamalKey.
5301
5302 Breaks in compatibility
5303 • Parameter segment_size cannot be 0 for the CFB mode.
5304
5305 • For OCB ciphers, a final call without parameters to encrypt must end
5306 a sequence of calls to encrypt with data (similarly for decrypt).
5307
5308 • Key size for ARC2, ARC4 and Blowfish must be at least 40 bits long
5309 (still very weak).
5310
5311 • DES3 (Triple DES module) does not allow keys that degenerate to Sin‐
5312 gle DES.
5313
5314 • Removed method getRandomNumber in Crypto.Util.number.
5315
5316 • Removed module Crypto.pct_warnings.
5317
5318 • Removed attribute Crypto.PublicKey.RSA.algorithmIdentifier.
5319
5320 3.3.1 (1 November 2015)
5321 New features
5322 • Opt-in for update() after digest() for SHA-3, keccak, BLAKE2 hashes
5323
5324 Resolved issues
5325 • Removed unused SHA-3 and keccak test vectors, therefore significantly
5326 reducing the package from 13MB to 3MB.
5327
5328 Breaks in compatibility
5329 • Removed method copy() from BLAKE2 hashes
5330
5331 • Removed ability to update() a BLAKE2 hash after the first call to
5332 (hex)digest()
5333
5334 3.3 (29 October 2015)
5335 New features
5336 • Windows wheels bundle the MPIR library
5337
5338 • Detection of faults occurring during secret RSA operations
5339
5340 • Detection of non-prime (weak) q value in DSA domain parameters
5341
5342 • Added original Keccak hash family (b=1600 only). In the process,
5343 simplified the C code base for SHA-3.
5344
5345 • Added SHAKE128 and SHAKE256 (of SHA-3 family)
5346
5347 Resolved issues
5348 • GH#3: gcc 4.4.7 unhappy about double typedef
5349
5350 Breaks in compatibility
5351 • Removed method copy() from all SHA-3 hashes
5352
5353 • Removed ability to update() a SHA-3 hash after the first call to
5354 (hex)digest()
5355
5356 3.2.1 (9 September 2015)
5357 New features
5358 • Windows wheels are automatically built on Appveyor
5359
5360 3.2 (6 September 2015)
5361 New features
5362 • Added hash functions BLAKE2b and BLAKE2s.
5363
5364 • Added stream cipher ChaCha20.
5365
5366 • Added OCB cipher mode.
5367
5368 • CMAC raises an exception whenever the message length is found to be
5369 too large and the chance of collisions not negligeable.
5370
5371 • New attribute oid for Hash objects with ASN.1 Object ID
5372
5373 • Added Crypto.Signature.pss and Crypto.Signature.pkcs1_15
5374
5375 • Added NIST test vectors (roughly 1200) for PKCS#1 v1.5 and PSS signa‐
5376 tures.
5377
5378 Resolved issues
5379 • tomcrypt_macros.h asm error #1
5380
5381 Breaks in compatibility
5382 • Removed keyword verify_x509_cert from module method importKey (RSA
5383 and DSA).
5384
5385 • Reverted to original PyCrypto behavior of method verify in PKCS1_v1_5
5386 and PKCS1_PSS.
5387
5388 3.1 (15 March 2015)
5389 New features
5390 • Speed up execution of Public Key algorithms on PyPy, when backed by
5391 the Gnu Multiprecision (GMP) library.
5392
5393 • GMP headers and static libraries are not required anymore at the time
5394 PyCryptodome is built. Instead, the code will automatically use the
5395 GMP dynamic library (.so/.DLL) if found in the system at runtime.
5396
5397 • Reduced the amount of C code by almost 40% (4700 lines). Modularized
5398 and simplified all code (C and Python) related to block ciphers. Py‐
5399 cryptodome is now free of CPython extensions.
5400
5401 • Add support for CI in Windows via Appveyor.
5402
5403 • RSA and DSA key generation more closely follows FIPS 186-4 (though it
5404 is not 100% compliant).
5405
5406 Resolved issues
5407 • None
5408
5409 Breaks in compatibility
5410 • New dependency on ctypes with Python 2.4.
5411
5412 • The counter parameter of a CTR mode cipher must be generated via
5413 Crypto.Util.Counter. It cannot be a generic callable anymore.
5414
5415 • Removed the Crypto.Random.Fortuna package (due to lack of test vec‐
5416 tors).
5417
5418 • Removed the Crypto.Hash.new function.
5419
5420 • The allow_wraparound parameter of Crypto.Util.Counter is ignored. An
5421 exception is always generated if the counter is reused.
5422
5423 • DSA.generate, RSA.generate and ElGamal.generate do not accept the
5424 progress_func parameter anymore.
5425
5426 • Removed Crypto.PublicKey.RSA.RSAImplementation.
5427
5428 • Removed Crypto.PublicKey.DSA.DSAImplementation.
5429
5430 • Removed ambiguous method size() from RSA, DSA and ElGamal keys.
5431
5432 3.0 (24 June 2014)
5433 New features
5434 • Initial support for PyPy.
5435
5436 • SHA-3 hash family based on the April 2014 draft of FIPS 202. See
5437 modules Crypto.Hash.SHA3_224/256/384/512. Initial Keccak patch by
5438 Fabrizio Tarizzo.
5439
5440 • Salsa20 stream cipher. See module Crypto.Cipher.Salsa20. Patch by
5441 Fabrizio Tarizzo.
5442
5443 • Colin Percival's scrypt key derivation function (Crypto.Proto‐
5444 col.KDF.scrypt).
5445
5446 • Proper interface to FIPS 186-3 DSA. See module Crypto.Signature.DSS.
5447
5448 • Deterministic DSA (RFC6979). Again, see Crypto.Signature.DSS.
5449
5450 • HMAC-based Extract-and-Expand key derivation function (Crypto.Proto‐
5451 col.KDF.HKDF, RFC5869).
5452
5453 • Shamir's Secret Sharing protocol, compatible with ssss (128 bits
5454 only). See module Crypto.Protocol.SecretSharing.
5455
5456 • Ability to generate a DSA key given the domain parameters.
5457
5458 • Ability to test installation with a simple python -m Crypto.SelfTest.
5459
5460 Resolved issues
5461 • LP#1193521: mpz_powm_sec() (and Python) crashed when modulus was odd.
5462
5463 • Benchmarks work again (they broke when ECB stopped working if an IV
5464 was passed. Patch by Richard Mitchell.
5465
5466 • LP#1178485: removed some catch-all exception handlers. Patch by
5467 Richard Mitchell.
5468
5469 • LP#1209399: Removal of Python wrappers caused HMAC to silently pro‐
5470 duce the wrong data with SHA-2 algorithms.
5471
5472 • LP#1279231: remove dead code that does nothing in SHA-2 hashes.
5473 Patch by Richard Mitchell.
5474
5475 • LP#1327081: AESNI code accesses memory beyond buffer end.
5476
5477 • Stricter checks on ciphertext and plaintext size for textbook RSA
5478 (kudos to sharego).
5479
5480 Breaks in compatibility
5481 • Removed support for Python < 2.4.
5482
5483 • Removed the following methods from all 3 public key object types
5484 (RSA, DSA, ElGamal):
5485
5486 • sign
5487
5488 • verify
5489
5490 • encrypt
5491
5492 • decrypt
5493
5494 • blind
5495
5496 • unblind
5497
5498 Code that uses such methods is doomed anyway. It should be fixed ASAP
5499 to use the algorithms available in Crypto.Signature and Crypto.Ci‐
5500 pher.
5501
5502 • The 3 public key object types (RSA, DSA, ElGamal) are now unpickable.
5503
5504 • Symmetric ciphers do not have a default mode anymore (used to be
5505 ECB). An expression like AES.new(key) will now fail. If ECB is the
5506 desired mode, one has to explicitly use AES.new(key, AES.MODE_ECB).
5507
5508 • Unsuccessful verification of a signature will now raise an exception
5509 [reverted in 3.2].
5510
5511 • Removed the Crypto.Random.OSRNG package.
5512
5513 • Removed the Crypto.Util.winrandom module.
5514
5515 • Removed the Crypto.Random.randpool module.
5516
5517 • Removed the Crypto.Cipher.XOR module.
5518
5519 • Removed the Crypto.Protocol.AllOrNothing module.
5520
5521 • Removed the Crypto.Protocol.Chaffing module.
5522
5523 • Removed the parameters disabled_shortcut and overflow from
5524 Crypto.Util.Counter.new.
5525
5526 Other changes
5527 • Crypto.Random stops being a userspace CSPRNG. It is now a pure wrap‐
5528 per over os.urandom.
5529
5530 • Added certain resistance against side-channel attacks for GHASH (GCM)
5531 and DSA.
5532
5533 • More test vectors for HMAC-RIPEMD-160.
5534
5535 • Update libtomcrypt headers and code to v1.17 (kudos to Richard
5536 Mitchell).
5537
5538 • RSA and DSA keys are checked for consistency as they are imported.
5539
5540 • Simplified build process by removing autoconf.
5541
5542 • Speed optimization to PBKDF2.
5543
5544 • Add support for MSVC.
5545
5546 • Replaced HMAC code with a BSD implementation. Clarified that starting
5547 from the fork, all contributions are released under the BSD license.
5548
5550 The source code in PyCryptodome is partially in the public domain and
5551 partially released under the BSD 2-Clause license.
5552
5553 In either case, there are minimal if no restrictions on the redistribu‐
5554 tion, modification and usage of the software.
5555
5556 Public domain
5557 All code originating from PyCrypto is free and unencumbered software
5558 released into the public domain.
5559
5560 Anyone is free to copy, modify, publish, use, compile, sell, or dis‐
5561 tribute this software, either in source code form or as a compiled bi‐
5562 nary, for any purpose, commercial or non-commercial, and by any means.
5563
5564 In jurisdictions that recognize copyright laws, the author or authors
5565 of this software dedicate any and all copyright interest in the soft‐
5566 ware to the public domain. We make this dedication for the benefit of
5567 the public at large and to the detriment of our heirs and successors.
5568 We intend this dedication to be an overt act of relinquishment in per‐
5569 petuity of all present and future rights to this software under copy‐
5570 right law.
5571
5572 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
5573 OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MER‐
5574 CHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
5575 NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
5576 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
5577 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
5578 DEALINGS IN THE SOFTWARE.
5579
5580 For more information, please refer to <http://unlicense.org>
5581
5582 BSD license
5583 All direct contributions to PyCryptodome are released under the follow‐
5584 ing license. The copyright of each piece belongs to the respective au‐
5585 thor.
5586
5587 Redistribution and use in source and binary forms, with or without mod‐
5588 ification, are permitted provided that the following conditions are
5589 met:
5590
5591 1. Redistributions of source code must retain the above copyright no‐
5592 tice, this list of conditions and the following disclaimer.
5593
5594 2. Redistributions in binary form must reproduce the above copyright
5595 notice, this list of conditions and the following disclaimer in the
5596 documentation and/or other materials provided with the distribution.
5597
5598 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
5599 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
5600 TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTIC‐
5601 ULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
5602 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
5603 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
5604 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
5605 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
5606 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
5607 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
5608 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
5609
5610 OCB license
5611 The OCB cipher mode is patented in the US under patent numbers
5612 7,949,129 and 8,321,675. The directory Doc/ocb contains three free li‐
5613 censes for implementors and users. As a general statement, OCB can be
5614 freely used for software not meant for military purposes. Contact your
5615 attorney for further information.
5616
5618 Legrandin
5619
5621 2021, Helder Eijs
5622
5623
5624
5625
56263.11 Oct 09, 2021 PYCRYPTODOME(1)