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