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