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