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