1PYCRYPTODOME(1)                  PyCryptodome                  PYCRYPTODOME(1)
2
3
4

NAME

6       pycryptodome - PyCryptodome Documentation .SH PYCRYPTODOME
7
8       PyCryptodome  is  a  self-contained Python package of low-level crypto‐
9       graphic primitives.
10
11       It supports Python 2.7, Python 3.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 in‐
17          stall it with:
18
19             pip install pycryptodome
20
21          In this case, all modules are installed under the Crypto package.
22
23          One must avoid having both PyCrypto and  PyCryptodome  installed  at
24          the same time, as they will interfere with each other.
25
26          This option is therefore recommended only when you are sure that the
27          whole application is deployed in a virtualenv.
28
29       2. a library independent of the old PyCrypto.  You install it with:
30
31             pip install pycryptodomex
32
33          In this case, all modules are installed under the  Cryptodome  pack‐
34          age.  PyCrypto and PyCryptodome can coexist.
35
36       For  faster  public  key  operations in Unix, you should install GMP in
37       your system.
38
39       PyCryptodome is a fork of PyCrypto. It brings  the  following  enhance‐
40       ments with respect to the last official version of PyCrypto (2.6.1):
41
42       • Authenticated encryption modes (GCM, CCM, EAX, SIV, OCB)
43
44       • Accelerated AES on Intel platforms via AES-NI
45
46       • First class support for PyPy
47
48       • Elliptic  curves  cryptography  (NIST  P-256,  P-384 and P-521 curves
49         only)
50
51       • Better and more compact API (nonce and iv attributes for ciphers, au‐
52         tomatic  generation  of  random nonces and IVs, simplified CTR cipher
53         mode, and more)
54
55       • SHA-3 (including SHAKE 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       For security issues, please send an email to security@pycryptodome.org.
89
90       All the code can be downloaded from GitHub.
91

FEATURES

93       This page lists the low-level primitives that PyCryptodome provides.
94
95       You  are expected to have a solid understanding of cryptography and se‐
96       curity engineering to successfully use them.
97
98       You must also be able to recognize that some  primitives  are  obsolete
99       (e.g.  TDES)  or  even unsecure (RC4). They are provided only to enable
100       backward compatibility where required by the applications.
101
102       A list of useful resources in that area can be found on Matthew Green's
103       blog.
104
105       • Symmetric ciphers:
106
107         • AES
108
109         • Single and Triple DES (legacy)
110
111         • CAST-128 (legacy)
112
113         • RC2 (legacy)
114
115       • Traditional modes of operations for symmetric ciphers:
116
117         • ECB
118
119         • CBC
120
121         • CFB
122
123         • OFB
124
125         • CTR
126
127         • OpenPGP (a variant of CFB, RFC4880)
128
129       • Authenticated Encryption:
130
131         • CCM (AES only)
132
133         • EAX
134
135         • GCM (AES only)
136
137         • SIV (AES only)
138
139         • OCB (AES only)
140
141         • ChaCha20-Poly1305
142
143       • Stream ciphers:
144
145         • Salsa20
146
147         • ChaCha20
148
149         • RC4 (legacy)
150
151       • Cryptographic hashes:
152
153         • SHA-1
154
155         • SHA-2 hashes (224, 256, 384, 512, 512/224, 512/256)
156
157         • SHA-3 hashes (224, 256, 384, 512) and XOFs (SHAKE128, SHAKE256)
158
159         • Keccak (original submission to SHA-3)
160
161         • BLAKE2b and BLAKE2s
162
163         • RIPE-MD160 (legacy)
164
165         • MD5 (legacy)
166
167       • Message Authentication Codes (MAC):
168
169         • HMAC
170
171         • CMAC
172
173         • Poly1305
174
175       • Asymmetric key generation:
176
177         • RSA
178
179         • ECC (NIST P-256, P-384 and P-521 curve only)
180
181         • DSA
182
183         • ElGamal (legacy)
184
185       • Export and import format for asymmetric keys:
186
187         • PEM (clear and encrypted)
188
189         • PKCS#8 (clear and encrypted)
190
191         • ASN.1 DER
192
193       • Asymmetric ciphers:
194
195         • PKCS#1 (RSA)
196
197           • RSAES-PKCS1-v1_5
198
199           • RSAES-OAEP
200
201       • Asymmetric digital signatures:
202
203         • PKCS#1 (RSA)
204
205           • RSASSA-PKCS1-v1_5
206
207           • RSASSA-PSS
208
209         • (EC)DSA
210
211           • Nonce-based (FIPS 186-3)
212
213           • Deterministic (RFC6979)
214
215       • Key derivation:
216
217         • PBKDF2
218
219         • scrypt
220
221         • HKDF
222
223         • PBKDF1 (legacy)
224
225       • Other cryptographic protocols:
226
227         • Shamir Secret Sharing
228
229         • Padding
230
231           • PKCS#7
232
233           • ISO-7816
234
235           • X.923
236

INSTALLATION

238       The  installation procedure depends on the package you want the library
239       to be in.  PyCryptodome can be used as:
240
241          1. an almost drop-in replacement for the old PyCrypto library.   You
242             install it with:
243
244                 pip install pycryptodome
245
246             In this case, all modules are installed under the Crypto package.
247             You can test everything is right with:
248
249                 pip install pycryptodome-test-vectors
250                 python -m Crypto.SelfTest
251
252             One must avoid having both PyCrypto and PyCryptodome installed at
253             the same time, as they will interfere with each other.
254
255             This  option is therefore recommended only when you are sure that
256             the whole application is deployed in a virtualenv.
257
258          2. a library independent of the old PyCrypto.  You install it with:
259
260                 pip install pycryptodomex
261
262             You can test everything is right with:
263
264                 pip install pycryptodome-test-vectors
265                 python -m Cryptodome.SelfTest
266
267             In this case, all modules  are  installed  under  the  Cryptodome
268             package.  PyCrypto and PyCryptodome can coexist.
269
270       The  procedures  below  go  a  bit more in detail, by explaining how to
271       setup the environment for compiling the C extensions for each  OS,  and
272       how to install the GMP library.
273
274   Compiling in Linux Ubuntu
275       NOTE:
276          If  you  want to install under the Crypto package, replace below py‐
277          cryptodomex with pycryptodome.
278
279       For Python 2.x:
280
281          $ sudo apt-get install build-essential python-dev
282          $ pip install pycryptodomex
283          $ pip install pycryptodome-test-vectors
284          $ python -m Cryptodome.SelfTest
285
286       For Python 3.x:
287
288          $ sudo apt-get install build-essential python3-dev
289          $ pip install pycryptodomex
290          $ pip install pycryptodome-test-vectors
291          $ python3 -m Cryptodome.SelfTest
292
293       For PyPy:
294
295          $ sudo apt-get install build-essential pypy-dev
296          $ pip install pycryptodomex
297          $ pip install pycryptodome-test-vectors
298          $ pypy -m Cryptodome.SelfTest
299
300   Compiling in Linux Fedora
301       NOTE:
302          If you want to install under the Crypto package, replace  below  py‐
303          cryptodomex with pycryptodome.
304
305       For Python 2.x:
306
307          $ sudo yum install gcc gmp python-devel
308          $ pip install pycryptodomex
309          $ pip install pycryptodome-test-vectors
310          $ python -m Cryptodome.SelfTest
311
312       For Python 3.x:
313
314          $ sudo yum install gcc gmp python3-devel
315          $ pip install pycryptodomex
316          $ pip install pycryptodome-test-vectors
317          $ python3 -m Cryptodome.SelfTest
318
319       For PyPy:
320
321          $ sudo yum install gcc gmp pypy-devel
322          $ pip install pycryptodomex
323          $ pip install pycryptodome-test-vectors
324          $ pypy -m Cryptodome.SelfTest
325
326   Windows (from sources, Python 2.x, Python <=3.2)
327       NOTE:
328          If  you  want to install under the Crypto package, replace below py‐
329          cryptodomex with pycryptodome.
330
331       Windows does not come with a C compiler like most  Unix  systems.   The
332       simplest way to compile the Pycryptodome extensions from source code is
333       to install the minimum set of  Visual  Studio  components  freely  made
334       available by Microsoft.
335
336       1. Run  Python  from  the  command  line  and note down its version and
337          whether it is a 32 bit or a 64 bit application.
338
339          For instance, if you see:
340
341             Python 2.7.2+ ... [MSC v.1500 32 bit (Intel)] on win32
342
343          you clearly have Python 2.7 and it is a 32 bit application.
344
345       2. [Only once] Install Virtual Clone Drive.
346
347       3. [Only once] Download the ISO image of the MS SDK for Windows 7 and .
348          NET Framework 3.5 SP1.  It contains the Visual C++ 2008 compiler.
349
350          There    are   three   ISO   images   available:   you   will   need
351          GRMSDK_EN_DVD.iso  if  your  Windows  OS  is  32   bits   or   GRMS‐
352          DKX_EN_DVD.iso if 64 bits.
353
354          Mount the ISO with Virtual Clone Drive and install the C/C++ compil‐
355          ers and the redistributable only.
356
357       4. If your Python is a 64 bit application, open a  command  prompt  and
358          perform the following steps:
359
360             > cd "C:\Program Files\Microsoft SDKs\Windows\v7.0"
361             > cmd /V:ON /K Bin\SetEnv.Cmd /x64 /release
362             > set DISTUTILS_USE_SDK=1
363
364          Replace /x64 with /x86 if your Python is a 32 bit application.
365
366       5. Compile and install PyCryptodome:
367
368             > pip install pycryptodomex --no-use-wheel
369
370       6. To make sure everything work fine, run the test suite:
371
372             > pip install pycryptodome-test-vectors
373             > python -m Cryptodome.SelfTest
374
375   Windows (from sources, Python 3.3 and 3.4)
376       NOTE:
377          If  you  want to install under the Crypto package, replace below py‐
378          cryptodomex with pycryptodome.
379
380       Windows does not come with a C compiler like most  Unix  systems.   The
381       simplest way to compile the Pycryptodome extensions from source code is
382       to install the minimum set of  Visual  Studio  components  freely  made
383       available by Microsoft.
384
385       1. Run  Python  from  the  command  line  and note down its version and
386          whether it is a 32 bit or a 64 bit application.
387
388          For instance, if you see:
389
390             Python 2.7.2+ ... [MSC v.1500 32 bit (Intel)] on win32
391
392          you clearly have Python 2.7 and it is a 32 bit application.
393
394       2. [Only once] Install Virtual Clone Drive.
395
396       3. [Only once] Download the ISO image of the MS SDK for Windows 7 and .
397          NET Framework 4.  It contains the Visual C++ 2010 compiler.
398
399          There    are   three   ISO   images   available:   you   will   need
400          GRMSDK_EN_DVD.iso  if  your  Windows  OS  is  32   bits   or   GRMS‐
401          DKX_EN_DVD.iso if 64 bits.
402
403          Mount the ISO with Virtual Clone Drive and install the C/C++ compil‐
404          ers and the redistributable only.
405
406       4. If your Python is a 64 bit application, open a  command  prompt  and
407          perform the following steps:
408
409             > cd "C:\Program Files\Microsoft SDKs\Windows\v7.1"
410             > cmd /V:ON /K Bin\SetEnv.Cmd /x64 /release
411             > set DISTUTILS_USE_SDK=1
412
413          Replace /x64 with /x86 if your Python is a 32 bit application.
414
415       5. Compile and install PyCryptodome:
416
417             > pip install pycryptodomex --no-use-wheel
418
419       6. To make sure everything work fine, run the test suite:
420
421             > pip install pycryptodome-test-vectors
422             > python -m Cryptodome.SelfTest
423
424   Windows (from sources, Python 3.5 and newer)
425       NOTE:
426          If  you  want to install under the Crypto package, replace below py‐
427          cryptodomex with pycryptodome.
428
429       Windows does not come with a C compiler like most  Unix  systems.   The
430       simplest way to compile the PyCryptodome extensions from source code is
431       to install the minimum set of  Visual  Studio  components  freely  made
432       available by Microsoft.
433
434       1. [Once only] Download Build Tools for Visual Studio 2019.  In the in‐
435          staller, select the C++ build tools, the Windows  10  SDK,  and  the
436          latest version of MSVC v142 x64/x86 build tools.
437
438       2. Compile and install PyCryptodome:
439
440             > pip install pycryptodomex --no-binary :all:
441
442       3. To make sure everything work fine, run the test suite:
443
444             > pip install pycryptodome-test-vectors
445             > python -m Cryptodome.SelfTest
446
447   Documentation
448       Project  documentation  is written in reStructuredText and it is stored
449       under Doc/src.  To publish it as HTML files, you need to install sphinx
450       and use:
451
452          > make -C Doc/ html
453
454       It will then be available under Doc/_build/html/.
455
456   PGP verification
457       All  source  packages  and wheels on PyPI are cryptographically signed.
458       They can be verified with the following PGP key:
459
460          -----BEGIN PGP PUBLIC KEY BLOCK-----
461
462          mQINBFTXjPgBEADc3j7vnma9MXRshBPPXXenVpthQD6lrF/3XaBT2RptSf/viOD+
463          tz85du5XVp+r0SYYGeMNJCQ9NsztxblN/lnKgkfWRmSrB+V6QGS+e3bR5d9OIxzN
464          7haPxBnyRj//hCT/kKis6fa7N9wtwKBBjbaSX+9vpt7Rrt203sKfcChA4iR3EG89
465          TNQoc/kGGmwk/gyjfU38726v0NOhMKJp2154iQQVZ76hTDk6GkOYHTcPxdkAj4jS
466          Dd74M9sOtoOlyDLHOLcWNnlWGgZjtz0z0qSyFXRSuOfggTxrepWQgKWXXzgVB4Jo
467          0bhmXPAV8vkX5BoG6zGkYb47NGGvknax6jCvFYTCp1sOmVtf5UTVKPplFm077tQg
468          0KZNAvEQrdWRIiQ1cCGCoF2Alex3VmVdefHOhNmyY7xAlzpP0c8z1DsgZgMnytNn
469          GPusWeqQVijRxenl+lyhbkb9ZLDq7mOkCRXSze9J2+5aLTJbJu3+Wx6BEyNIHP/f
470          K3E77nXvC0oKaYTbTwEQSBAggAXP+7oQaA0ea2SLO176xJdNfC5lkQEtMMSZI4gN
471          iSqjUxXW2N5qEHHex1atmTtk4W9tQEw030a0UCxzDJMhD0aWFKq7wOxoCQ1q821R
472          vxBH4cfGWdL/1FUcuCMSUlc6fhTM9pvMXgjdEXcoiLSTdaHuVLuqmF/E0wARAQAB
473          tB9MZWdyYW5kaW4gPGhlbGRlcmlqc0BnbWFpbC5jb20+iQI4BBMBAgAiBQJU14z4
474          AhsDBgsJCAcDAgYVCAIJCgsEFgIDAQIeAQIXgAAKCRDabO+N4RaZEn7IEACpApha
475          vRwPB+Dv87aEyVmjZ96Nb3mxHdeP2uSmUxAODzoB5oJJ1QL6HRxEVlU8idjdf73H
476          DX39ZC7izD+oYIve9sNwTbKqJCZaTxlTDdgSF1N57eJOlELAy+SqpHtaMJPk7SfJ
477          l/iYoUYxByPLZU1wDwZEDNzt9RCGy3bd/vF/AxWjdUJJPh3E4j5hswvIGSf8/Tp3
478          MDROU1BaNBOd0CLvBHok8/xavwO6Dk/fE4hJhd5uZcEPtd1GJcPq51z2yr7PGUcb
479          oERsKZyG8cgfd7j8qoTd6jMIW6fBVHdxiMxW6/Z45X/vVciQSzzEl/yjPUW42kyr
480          Ib6M16YmnDzp8bl4NNFvvR9uWvOdUkep2Bi8s8kBMJ7G9rHHJcdVy/tP1ECS9Bse
481          hN4v5oJJ4v5mM/MiWRGKykZULWklonpiq6CewYkmXQDMRnjGXhjCWrB6LuSIkIXd
482          gKvDNpJ8yEhAfmpvA4I3laMoof/tSZ7ZuyLSZGLKl6hoNIB13HCn4dnjNBeaXCWX
483          pThgeOWxV6u1fhz4CeC1Hc8WOYr8S7G8P10Ji6owOcj/a1QuCW8XDB2omCTXlhFj
484          zpC9dX8HgmUVnbPNiMjphihbKXoOcunRx4ZvqIa8mnTbI4tHtR0K0tI4MmbpcVOZ
485          8IFJ0nZJXuZiL57ijLREisPYmHfBHAgmh1j/W7kCDQRU14z4ARAA3QATRgvOSYFh
486          nJOnIz6PO3G9kXWjJ8wvp3yE1/PwwTc3NbVUSNCW14xgM2Ryhn9NVh8iEGtPGmUP
487          4vu7rvuLC2rBs1joBTyqf0mDghlZrb5ZjXv5LcG9SA6FdAXRU6T+b1G2ychKkhEh
488          d/ulLw/TKLds9zHhE+hkAagLQ5jqjcQN0iX5EYaOukiPUGmnd9fOEGi9YMYtRdrH
489          +3bZxUpsRStLBWJ6auY7Bla8NJOhaWpr5p/ls+mnDWoqf+tXCCps1Da/pfHKYDFc
490          2VVdyM/VfNny9eaczYpnj5hvIAACWChgGDBwxPh2DGdUfiQi/QqrK96+F7ulqz6V
491          2exX4CL0cPv5fUpQqSU/0R5WApM9bl2+wljFhoCXlydU9HNn+0GatGzEoo3yrV/m
492          PXv7d6NdZxyOqgxu/ai/z++F2pWUXSBxZN3Gv28boFKQhmtthTcFudNUtQOchhn8
493          Pf/ipVISqrsZorTx9Qx4fPScEWjwbh84Uz20bx0sQs1oYcek2YG5RhEdzqJ6W78R
494          S/dbzlNYMXGdkxB6C63m8oiGvw0hdN/iGVqpNAoldFmjnFqSgKpyPwfLmmdstJ6f
495          xFZdGPnKexCpHbKr9fg50jZRenIGai79qPIiEtCZHIdpeemSrc7TKRPV3H2aMNfG
496          L5HTqcyaM2+QrMtHPMoOFzcjkigLimMAEQEAAYkCHwQYAQIACQUCVNeM+AIbDAAK
497          CRDabO+N4RaZEo7lD/45J6z2wbL8aIudGEL0aY3hfmW3qrUyoHgaw35KsOY9vZwb
498          cZuJe0RlYptOreH/NrbR5SXODfhd2sxYyyvXBOuZh9i7OOBsrAd5UE01GCvToPwh
499          7IpMV3GSSAB4P8XyJh20tZqiZOYKhmbf29gUDzqAI6GzUa0U8xidUKpW2zqYGZjp
500          wk3RI1fS7tyi/0N8B9tIZF48kbvpFDAjF8w7NSCrgRquAL7zJZIG5o5zXJM/ffF3
501          67Dnz278MbifdM/HJ+Tj0R0Uvvki9Z61nT653SoUgvILQyC72XI+x0+3GQwsE38a
502          5aJNZ1NBD3/v+gERQxRfhM5iLFLXK0Xe4K2XFM1g0yN4L4bQPbhSCq88g9Dhmygk
503          XPbBsrK0NKPVnyGyUXM0VpgRbot11hxx02jC3HxS1nlLF+oQdkKFzJAMOU7UbpX/
504          oO+286J1FmpG+fihIbvp1Quq48immtnzTeLZbYCsG4mrM+ySYd0Er0G8TBdAOTiN
505          3zMbGX0QOO2fOsJ1d980cVjHn5CbAo8C0A/4/R2cXAfpacbvTiNq5BVk9NKa2dNb
506          kmnTStP2qILWmm5ASXlWhOjWNmptvsUcK+8T+uQboLioEv19Ob4j5Irs/OpOuP0K
507          v4woCi9+03HMS42qGSe/igClFO3+gUMZg9PJnTJhuaTbytXhUBgBRUPsS+lQAQ==
508          =DpoI
509          -----END PGP PUBLIC KEY BLOCK-----
510

COMPATIBILITY WITH PYCRYPTO

512       PyCryptodome exposes almost the same API as the old  PyCrypto  so  that
513       most  applications  will run unmodified.  However, a very few breaks in
514       compatibility had to be introduced for those parts of the API that rep‐
515       resented a security hazard or that were too hard to maintain.
516
517       Specifically, for public key cryptography:
518
519       • The  following  methods  from  public key objects (RSA, DSA, ElGamal)
520         have been removed:
521
522sign()
523
524verify()
525
526encrypt()
527
528decrypt()
529
530blind()
531
532unblind()
533
534         Applications should be updated to use instead:
535
536Crypto.Cipher.PKCS1_OAEP for encrypting using RSA.
537
538Crypto.Signature.pkcs1_15 or Crypto.Signature.pss for signing using
539           RSA.
540
541Crypto.Signature.DSS for signing using DSA.
542
543       • Method:  generate()  for  public  key  modules  does  not  accept the
544         progress_func parameter anymore.
545
546       • Ambiguous method size from RSA, DSA and ElGamal key objects have been
547         removed.  Instead, use methods size_in_bytes() and size_in_bits() and
548         check the documentation.
549
550       • The 3 public key object types (RSA, DSA, ElGamal) are now unpickable.
551         You  must use the export_key() method of each key object and select a
552         good output format: for private keys that means a good password-based
553         encryption scheme.
554
555       • Removed attribute Crypto.PublicKey.RSA.algorithmIdentifier.
556
557       • Removed  Crypto.PublicKey.RSA.RSAImplementation  (which  should  have
558         been  private  in   the   first   place).    Same   for   Crypto.Pub‐
559         licKey.DSA.DSAImplementation.
560
561       For symmetric key cryptography:
562
563       • Symmetric ciphers do not have ECB as default mode anymore. ECB is not
564         semantically secure and it exposes correlation across blocks.  An ex‐
565         pression like AES.new(key) will now fail. If ECB is the desired mode,
566         one has to explicitly use AES.new(key, AES.MODE_ECB).
567
568Crypto.Cipher.DES3 does not allow keys that degenerate to Single DES.
569
570       • Parameter segment_size cannot be 0 for the CFB mode.
571
572       • Parameters disabled_shortcut and overflow cannot be passed anymore to
573         Crypto.Util.Counter.new.    Parameter   allow_wraparound  is  ignored
574         (counter block wraparound will always be checked).
575
576       • The counter parameter of a CTR mode  cipher  must  be  generated  via
577         Crypto.Util.Counter. It cannot be a generic callable anymore.
578
579       • Keys   for   Crypto.Cipher.ARC2,  Crypto.Cipher.ARC4  and  Crypto.Ci‐
580         pher.Blowfish must be at least 40 bits long (still very weak).
581
582       The following packages, modules and functions have been removed:
583
584Crypto.Random.OSRNG, Crypto.Util.winrandom and Crypto.Random.rand‐
585            pool.  You should use Crypto.Random only.
586
587Crypto.Cipher.XOR.   If   you   just   want   to   XOR  data,  use
588            Crypto.Util.strxor.
589
590Crypto.Hash.new. Use Crypto.Hash.<algorithm>.new() instead.
591
592Crypto.Protocol.AllOrNothing
593
594Crypto.Protocol.Chaffing
595
596Crypto.Util.number.getRandomNumber
597
598Crypto.pct_warnings
599
600       Others:
601
602       • Support for any Python version older than 2.6 is dropped.
603

API DOCUMENTATION

605   Crypto.Cipher package
606   Introduction
607       The Crypto.Cipher package contains algorithms for protecting the confi‐
608       dentiality of data.
609
610       There are three types of encryption algorithms:
611
612       1. Symmetric ciphers: all parties use the same key, for both decrypting
613          and encrypting data.  Symmetric ciphers are typically very fast  and
614          can process very large amount of data.
615
616       2. Asymmetric  ciphers:  senders  and  receivers  use  different  keys.
617          Senders encrypt with public keys (non-secret) whereas receivers  de‐
618          crypt  with private keys (secret).  Asymmetric ciphers are typically
619          very slow and can process only very small payloads. Example: oaep.
620
621       3. Hybrid ciphers: the two types of ciphers above can be combined in  a
622          construction  that inherits the benefits of both.  An asymmetric ci‐
623          pher is used to protect a short-lived symmetric key, and a symmetric
624          cipher (under that key) encrypts the actual message.
625
626   API principles
627         [image] Generic state diagram for a cipher object.UNINDENT
628
629         The base API of a cipher is fairly simple:
630
631       • You  instantiate  a  cipher object by calling the new() function from
632         the relevant cipher module (e.g. Crypto.Cipher.AES.new()).  The first
633         parameter  is always the cryptographic key; its length depends on the
634         particular cipher.  You can (and sometimes must) pass additional  ci‐
635         pher- or mode-specific parameters to new() (such as a nonce or a mode
636         of operation).
637
638       • For encrypting data, you call the encrypt() method of the cipher  ob‐
639         ject  with the plaintext. The method returns the piece of ciphertext.
640         Alternatively, with the output parameter you can specify a  pre-allo‐
641         cated buffer for the result.
642
643         For most algorithms, you may call encrypt() multiple times (i.e. once
644         for each piece of plaintext).
645
646       • For decrypting data, you call the decrypt() method of the cipher  ob‐
647         ject  with the ciphertext. The method returns the piece of plaintext.
648         The output parameter can be passed here too.
649
650          For most algorithms, you may call decrypt() multiple times
651                 (i.e. once for each piece of ciphertext).
652
653       NOTE:
654          Plaintexts and ciphertexts (input/output) can only be bytes, bytear‐
655          ray or memoryview.  In Python 3, you cannot pass strings.  In Python
656          2, you cannot pass Unicode strings.
657
658       Often, the sender has to deliver to the receiver other data in addition
659       to  ciphertext  alone (e.g. initialization vectors or nonces, MAC tags,
660       etc).
661
662       This is a basic example:
663
664          >>> from Crypto.Cipher import Salsa20
665          >>>
666          >>> key = b'0123456789012345'
667          >>> cipher = Salsa20.new(key)
668          >>> ciphertext =  cipher.encrypt(b'The secret I want to send.')
669          >>> ciphertext += cipher.encrypt(b'The second part of the secret.')
670          >>> print cipher.nonce  # A byte string you must send to the receiver too
671
672   Symmetric ciphers
673       There are two types of symmetric ciphers:
674
675Stream ciphers: the most natural kind of ciphers: they  encrypt  data
676         one byte at a time.  See chacha20 and salsa20.
677
678Block  ciphers:  ciphers  that  can only operate on a fixed amount of
679         data. The most important block cipher is aes, which has a block  size
680         of 128 bits (16 bytes).
681
682         In general, a block cipher is mostly useful only together with a mode
683         of operation, which allows one to encrypt a variable amount of  data.
684         Some  modes  (like CTR) effectively turn a block cipher into a stream
685         cipher.
686
687       The widespread consensus is that ciphers that  provide  only  confiden‐
688       tiality, without any form of authentication, are undesirable.  Instead,
689       primitives have been defined to integrate symmetric encryption and  au‐
690       thentication (MAC). For instance:
691
692       • Modern modes of operation for block ciphers (like GCM).
693
694       • Stream ciphers paired with a MAC function, like chacha20_poly1305.
695
696   Classic modes of operation for symmetric block ciphers
697       A  block  cipher uses a symmetric key to encrypt data of fixed and very
698       short length (the block size), such as 16 bytes for AES.  In  order  to
699       cope  with data of arbitrary length, the cipher must be combined with a
700       mode of operation.
701
702       You create a cipher object with the new() function in the relevant mod‐
703       ule under Crypto.Cipher:
704
705       1. the first parameter is always the cryptographic key (a byte string)
706
707       2. the second parameter is always the constant that selects the desired
708          mode of operation
709
710       Constants for each mode of operation are defined at  the  module  level
711       for  each  algorithm.   Their  name  starts  with  MODE_,  for instance
712       Crypto.Cipher.AES.MODE_CBC.  Note that  not  all  ciphers  support  all
713       modes.
714
715       For instance:
716
717          >>> from Crypto.Cipher import AES
718          >>> from Crypto.Random import get_random_bytes
719          >>>
720          >>> key = get_random_bytes(16)
721          >>> cipher = AES.new(key, AES.MODE_CBC)
722          >>>
723          >>> # You can now use use cipher to encrypt or decrypt...
724
725       The state machine for a cipher configured with a classic mode is:
726         [image] Generic state diagram for a cipher object.UNINDENT
727
728         What  follows  is a list of classic modes of operation: they all pro‐
729         vide confidentiality but  not  data  integrity  (unlike  modern  AEAD
730         modes, which are described in another section).
731
732   ECB mode
733       Electronic CodeBook.  The most basic but also the weakest mode of oper‐
734       ation.  Each block of plaintext is encrypted independently of any other
735       block.
736
737       WARNING:
738          The ECB mode should not be used because it is semantically insecure.
739          For one, it exposes correlation between blocks.
740
741       The new() function at the module level under Crypto.Cipher instantiates
742       a  new  ECB cipher object for the relevant base algorithm.  In the fol‐
743       lowing definition, <algorithm> could be AES:
744
745       Crypto.Cipher.<algorithm>.new(key, mode)
746              Create a new ECB object, using <algorithm> as the base block ci‐
747              pher.
748
749              Parameters
750
751key (bytes) -- the cryptographic key
752
753mode -- the constant Crypto.Cipher.<algorithm>.MODE_ECB
754
755              Returns
756                     an ECB cipher object
757
758       The  method  encrypt() (and likewise decrypt()) of an ECB cipher object
759       expects data to have length multiple of the block size (e.g.  16  bytes
760       for  AES).   You  might  need  to  use Crypto.Util.Padding to align the
761       plaintext to the right boundary.
762
763   CBC mode
764       Ciphertext Block Chaining, defined in NIST SP 800-38A, section 6.2.  It
765       is  a mode of operation where each plaintext block gets XOR-ed with the
766       previous ciphertext block prior to encryption.
767
768       The new() function at the module level under Crypto.Cipher instantiates
769       a  new  CBC cipher object for the relevant base algorithm.  In the fol‐
770       lowing definition, <algorithm> could be AES:
771
772       Crypto.Cipher.<algorithm>.new(key, mode, *, iv=None)
773              Create a new CBC object, using <algorithm> as the base block ci‐
774              pher.
775
776              Parameters
777
778key (bytes) -- the cryptographic key
779
780mode -- the constant Crypto.Cipher.<algorithm>.MODE_CBC
781
782iv  (bytes)  --  the  Initialization Vector. A piece of
783                       data unpredictable to adversaries.  It is  as  long  as
784                       the  block  size  (e.g.  16  bytes  for  AES).   If not
785                       present, the library creates a random IV value.
786
787              Returns
788                     a CBC cipher object
789
790       The method encrypt() (and likewise decrypt()) of a  CBC  cipher  object
791       expects  data  to have length multiple of the block size (e.g. 16 bytes
792       for AES).  You might need  to  use  Crypto.Util.Padding  to  align  the
793       plaintext to the right boundary.
794
795       A  CBC cipher object has a read-only attribute iv, holding the Initial‐
796       ization Vector (bytes).
797
798       Example (encryption):
799
800          >>> import json
801          >>> from base64 import b64encode
802          >>> from Crypto.Cipher import AES
803          >>> from Crypto.Util.Padding import pad
804          >>> from Crypto.Random import get_random_bytes
805          >>>
806          >>> data = b"secret"
807          >>> key = get_random_bytes(16)
808          >>> cipher = AES.new(key, AES.MODE_CBC)
809          >>> ct_bytes = cipher.encrypt(pad(data, AES.block_size))
810          >>> iv = b64encode(cipher.iv).decode('utf-8')
811          >>> ct = b64encode(ct_bytes).decode('utf-8')
812          >>> result = json.dumps({'iv':iv, 'ciphertext':ct})
813          >>> print(result)
814          '{"iv": "bWRHdzkzVDFJbWNBY0EwSmQ1UXFuQT09", "ciphertext": "VDdxQVo3TFFCbXIzcGpYa1lJbFFZQT09"}'
815
816       Example (decryption):
817
818          >>> import json
819          >>> from base64 import b64decode
820          >>> from Crypto.Cipher import AES
821          >>> from Crypto.Util.Padding import unpad
822          >>>
823          >>> # We assume that the key was securely shared beforehand
824          >>> try:
825          >>>     b64 = json.loads(json_input)
826          >>>     iv = b64decode(b64['iv'])
827          >>>     ct = b64decode(b64['ciphertext'])
828          >>>     cipher = AES.new(key, AES.MODE_CBC, iv)
829          >>>     pt = unpad(cipher.decrypt(ct), AES.block_size)
830          >>>     print("The message was: ", pt)
831          >>> except ValueError, KeyError:
832          >>>     print("Incorrect decryption")
833
834   CTR mode
835       CounTeR mode, defined in NIST SP 800-38A, section 6.5 and  Appendix  B.
836       This  mode  turns  the block cipher into a stream cipher.  Each byte of
837       plaintext is XOR-ed with a byte taken from a keystream: the  result  is
838       the ciphertext.  The keystream is generated by encrypting a sequence of
839       counter blocks with ECB.
840         [image]
841
842       A counter block is exactly as long as the cipher block  size  (e.g.  16
843       bytes for AES).  It consist of the concatenation of two pieces:
844
845       1. a fixed nonce, set at initialization.
846
847       2. a  variable  counter,  which  gets increased by 1 for any subsequent
848          counter block.  The counter is big endian encoded.
849
850       The new() function at the module level under Crypto.Cipher instantiates
851       a  new  CTR cipher object for the relevant base algorithm.  In the fol‐
852       lowing definition, <algorithm> could be AES:
853
854       Crypto.Cipher.<algorithm>.new(key,   mode,    *,    nonce=None,    ini‐
855       tial_value=None, counter=None)
856              Create a new CTR object, using <algorithm> as the base block ci‐
857              pher.
858
859              Parameters
860
861key (bytes) -- the cryptographic key
862
863mode -- the constant Crypto.Cipher.<algorithm>.MODE_CTR
864
865nonce (bytes) -- the value of the fixed nonce.  It must
866                       be  unique for the combination message/key.  Its length
867                       varies from 0 to  the  block  size  minus  1.   If  not
868                       present,  the  library creates a random nonce of length
869                       equal to block size/2.
870
871initial_value (integer or bytes) -- the  value  of  the
872                       counter  for the first counter block.  It can be either
873                       an integer or bytes (which is the  same  integer,  just
874                       big  endian  encoded).   If  not specified, the counter
875                       starts at 0.
876
877counter  --  a  custom  counter  object  created   with
878                       Crypto.Util.Counter.new().   This allows the definition
879                       of a more complex counter block.
880
881              Returns
882                     a CTR cipher object
883
884       The methods encrypt() and decrypt() of a CTR cipher object accept  data
885       of  any length (i.e. padding is not needed).  Both raise an OverflowEr‐
886       ror exception as soon as the counter wraps around to repeat the  origi‐
887       nal value.
888
889       The CTR cipher object has a read-only attribute nonce (bytes).
890
891       Example (encryption):
892
893          >>> import json
894          >>> from base64 import b64encode
895          >>> from Crypto.Cipher import AES
896          >>> from Crypto.Random import get_random_bytes
897          >>>
898          >>> data = b"secret"
899          >>> key = get_random_bytes(16)
900          >>> cipher = AES.new(key, AES.MODE_CTR)
901          >>> ct_bytes = cipher.encrypt(data)
902          >>> nonce = b64encode(cipher.nonce).decode('utf-8')
903          >>> ct = b64encode(ct_bytes).decode('utf-8')
904          >>> result = json.dumps({'nonce':nonce, 'ciphertext':ct})
905          >>> print(result)
906          {"nonce": "XqP8WbylRt0=", "ciphertext": "Mie5lqje"}
907
908       Example (decryption):
909
910          >>> import json
911          >>> from base64 import b64decode
912          >>> from Crypto.Cipher import AES
913          >>>
914          >>> # We assume that the key was securely shared beforehand
915          >>> try:
916          >>>     b64 = json.loads(json_input)
917          >>>     nonce = b64decode(b64['nonce'])
918          >>>     ct = b64decode(b64['ciphertext'])
919          >>>     cipher = AES.new(key, AES.MODE_CTR, nonce=nonce)
920          >>>     pt = cipher.decrypt(ct)
921          >>>     print("The message was: ", pt)
922          >>> except ValueError, KeyError:
923          >>>     print("Incorrect decryption")
924
925   CFB mode
926       Cipher FeedBack, defined in NIST SP 800-38A, section 6.3.  It is a mode
927       of operation which turns the block cipher into a stream  cipher.   Each
928       byte of plaintext is XOR-ed with a byte taken from a keystream: the re‐
929       sult is the ciphertext.
930
931       The keystream is obtained on a per-segment basis: the plaintext is bro‐
932       ken  up  in segments (from 1 byte up to the size of a block). Then, for
933       each segment, the keystream is obtained by encrypting  with  the  block
934       cipher  the  last  piece of ciphertext produced so far - possibly back‐
935       filled with the Initialization Vector,  if  not  enough  ciphertext  is
936       available yet.
937
938       The new() function at the module level under Crypto.Cipher instantiates
939       a new CFB cipher object for the relevant base algorithm.  In  the  fol‐
940       lowing definition, <algorithm> could be AES:
941
942       Crypto.Cipher.<algorithm>.new(key, mode, *, iv=None, segment_size=8)
943              Create a new CFB object, using <algorithm> as the base block ci‐
944              pher.
945
946              Parameters
947
948key (bytes) -- the cryptographic key
949
950mode -- the constant Crypto.Cipher.<algorithm>.MODE_CFB
951
952iv (bytes) -- the Initialization Vector.   It  must  be
953                       unique  for the combination message/key.  It is as long
954                       as the block size (e.g. 16  bytes  for  AES).   If  not
955                       present, the library creates a random IV.
956
957segment_size  (integer)  --  the  number  of  bits (not
958                       bytes!) the plaintext and the ciphertext are  segmented
959                       in (default if not specified: 8 bits = 1 byte).
960
961              Returns
962                     a CFB cipher object
963
964       The  methods encrypt() and decrypt() of a CFB cipher object accept data
965       of any length (i.e. padding is not needed).
966
967       The CFB cipher object has a read-only attribute iv (bytes), holding the
968       Initialization Vector.
969
970       Example (encryption):
971
972          >>> import json
973          >>> from base64 import b64encode
974          >>> from Crypto.Cipher import AES
975          >>> from Crypto.Random import get_random_bytes
976          >>>
977          >>> data = b"secret"
978          >>> key = get_random_bytes(16)
979          >>> cipher = AES.new(key, AES.MODE_CFB)
980          >>> ct_bytes = cipher.encrypt(data)
981          >>> iv = b64encode(cipher.iv).decode('utf-8')
982          >>> ct = b64encode(ct_bytes).decode('utf-8')
983          >>> result = json.dumps({'iv':iv, 'ciphertext':ct})
984          >>> print(result)
985          {"iv": "VoamO23kFSOZcK1O2WiCDQ==", "ciphertext": "f8jciJ8/"}
986
987       Example (decryption):
988
989          >>> import json
990          >>> from base64 import b64decode
991          >>> from Crypto.Cipher import AES
992          >>>
993          >>> # We assume that the key was securely shared beforehand
994          >>> try:
995          >>>     b64 = json.loads(json_input)
996          >>>     iv = b64decode(b64['iv'])
997          >>>     ct = b64decode(b64['ciphertext'])
998          >>>     cipher = AES.new(key, AES.MODE_CFB, iv=iv)
999          >>>     pt = cipher.decrypt(ct)
1000          >>>     print("The message was: ", pt)
1001          >>> except ValueError, KeyError:
1002          >>>     print("Incorrect decryption")
1003
1004   OFB mode
1005       Output  FeedBack,  defined  in NIST SP 800-38A, section 6.4.  It is an‐
1006       other mode that leads to a stream cipher.  Each byte  of  plaintext  is
1007       XOR-ed  with  a  byte taken from a keystream: the result is the cipher‐
1008       text.  The keystream is obtained by recursively encrypting the Initial‐
1009       ization Vector.
1010
1011       The new() function at the module level under Crypto.Cipher instantiates
1012       a new OFB cipher object for the relevant base algorithm.  In  the  fol‐
1013       lowing definition, <algorithm> could be AES:
1014
1015       Crypto.Cipher.<algorithm>.new(key, mode, *, iv=None)
1016              Create a new OFB object, using <algorithm> as the base block ci‐
1017              pher.
1018
1019              Parameters
1020
1021key (bytes) -- the cryptographic key
1022
1023mode -- the constant Crypto.Cipher.<algorithm>.MODE_OFB
1024
1025iv (bytes) -- the Initialization Vector.   It  must  be
1026                       unique  for the combination message/key.  It is as long
1027                       as the block size (e.g. 16  bytes  for  AES).   If  not
1028                       present, the library creates a random IV.
1029
1030              Returns
1031                     an OFB cipher object
1032
1033       The methods encrypt() and decrypt() of an OFB cipher object accept data
1034       of any length (i.e. padding is not needed).
1035
1036       The OFB cipher object has a read-only attribute iv (bytes), holding the
1037       Initialization Vector.
1038
1039       Example (encryption):
1040
1041          >>> import json
1042          >>> from base64 import b64encode
1043          >>> from Crypto.Cipher import AES
1044          >>> from Crypto.Random import get_random_bytes
1045          >>>
1046          >>> data = b"secret"
1047          >>> key = get_random_bytes(16)
1048          >>> cipher = AES.new(key, AES.MODE_OFB)
1049          >>> ct_bytes = cipher.encrypt(data)
1050          >>> iv = b64encode(cipher.iv).decode('utf-8')
1051          >>> ct = b64encode(ct_bytes).decode('utf-8')
1052          >>> result = json.dumps({'iv':iv, 'ciphertext':ct})
1053          >>> print(result)
1054          {"iv": "NUuRJbL0UMp8+UMCk2/vQA==", "ciphertext": "XGVGc1Gw"}
1055
1056       Example (decryption):
1057
1058          >>> import json
1059          >>> from base64 import b64decode
1060          >>> from Crypto.Cipher import AES
1061          >>>
1062          >>> # We assume that the key was securely shared beforehand
1063          >>> try:
1064          >>>     b64 = json.loads(json_input)
1065          >>>     iv = b64decode(b64['iv'])
1066          >>>     ct = b64decode(b64['ciphertext'])
1067          >>>     cipher = AES.new(key, AES.MODE_OFB, iv=iv)
1068          >>>     pt = cipher.decrypt(ct)
1069          >>>     print("The message was: ", pt)
1070          >>> except ValueError, KeyError:
1071          >>>     print("Incorrect decryption")
1072
1073   OpenPGP mode
1074       Constant: Crypto.Cipher.<cipher>.MODE_OPENPGP.
1075
1076       OpenPGP (defined in RFC4880).  A variant of CFB, with two differences:
1077
1078       1. The  first  invocation to the encrypt() method returns the encrypted
1079          IV concatenated to the first chunk of ciphertext (as opposed to  the
1080          ciphertext  only).   The  encrypted  IV is as long as the block size
1081          plus 2 more bytes.
1082
1083       2. When the cipher object is intended for decryption, the parameter  iv
1084          to  new()  is  the  encrypted IV (and not the IV, which is still the
1085          case for encryption).
1086
1087       Like for CTR, an OpenPGP cipher object has a read-only attribute iv.
1088
1089   Modern modes of operation for symmetric block ciphers
1090       Classic modes of operation such as CBC only provide guarantees over the
1091       confidentiality  of  the  message but not over its integrity.  In other
1092       words, they don't allow the receiver to establish if the ciphertext was
1093       modified in transit or if it really originates from a certain source.
1094
1095       For that reason, classic modes of operation have been often paired with
1096       a MAC primitive (such as Crypto.Hash.HMAC), but the combination is  not
1097       always straightforward, efficient or secure.
1098
1099       Recently,  new  modes of operations (AEAD, for Authenticated Encryption
1100       with Associated Data) have been designed to combine encryption and  au‐
1101       thentication  into a single, efficient primitive. Optionally, some part
1102       of the message can also be left in the clear (non-confidential  associ‐
1103       ated  data, such as headers), while the whole message remains fully au‐
1104       thenticated.
1105
1106       In addition to the ciphertext and a nonce (or IV - Initialization  Vec‐
1107       tor), AEAD modes require the additional delivery of a MAC tag.
1108
1109       This is the state machine for a cipher object:
1110         [image] Generic state diagram for a AEAD cipher mode.UNINDENT
1111
1112         Beside  the usual encrypt() and decrypt() already available for clas‐
1113         sic modes of operation, several other methods are present:
1114
1115       update(data)
1116              Authenticate those parts of the message that  get  delivered  as
1117              is, without any encryption (like headers).  It is similar to the
1118              update() method of a MAC object.  Note that all data  passed  to
1119              encrypt() and decrypt() get automatically authenticated already.
1120
1121              Parameters
1122                     data (bytes) -- the extra data to authenticate
1123
1124       digest()
1125              Create the final authentication tag (MAC tag) for a message.
1126
1127              Return bytes
1128                     the MAC tag
1129
1130       hexdigest()
1131              Equivalent to digest(), with the output encoded in hexadecimal.
1132
1133              Return str
1134                     the MAC tag as a hexadecimal string
1135
1136       verify(mac_tag)
1137              Check  if  the  provided  authentication tag (MAC tag) is valid,
1138              that is, if the message has been decrypted using the  right  key
1139              and if no modification has taken place in transit.
1140
1141              Parameters
1142                     mac_tag (bytes) -- the MAC tag
1143
1144              Raises ValueError  --  if  the MAC tag is not valid, that is, if
1145                     the entire message should not be trusted.
1146
1147       hexverify(mac_tag_hex)
1148              Same as verify() but accepts the MAC tag encoded as an hexadeci‐
1149              mal string.
1150
1151              Parameters
1152                     mac_tag_hex (str) -- the MAC tag as a hexadecimal string
1153
1154              Raises ValueError  --  if  the MAC tag is not valid, that is, if
1155                     the entire message should not be trusted.
1156
1157       encrypt_and_digest(plaintext, output=None)
1158              Perform encrypt() and digest() in one go.
1159
1160              Parameters
1161                     plaintext (bytes) -- the last piece of plaintext  to  en‐
1162                     crypt
1163
1164              Keyword Arguments
1165                     output  (bytes/bytearray/memoryview) -- the pre-allocated
1166                     buffer where the ciphertext must be stored (as opposed to
1167                     being returned).
1168
1169              Returns
1170                     a tuple with two items
1171
1172                     • the ciphertext, as bytes
1173
1174                     • the MAC tag, as bytes
1175
1176                     The  first  item  becomes  None when the output parameter
1177                     specified a location for the result.
1178
1179
1180       decrypt_and_verify(ciphertext, mac_tag, output=None)
1181              Perform decrypt() and verify() in one go.
1182
1183              Parameters
1184                     ciphertext (bytes) -- the last piece of ciphertext to de‐
1185                     crypt
1186
1187              Keyword Arguments
1188                     output  (bytes/bytearray/memoryview) -- the pre-allocated
1189                     buffer where the plaintext must be stored (as opposed  to
1190                     being returned).
1191
1192              Raises ValueError  --  if  the MAC tag is not valid, that is, if
1193                     the entire message should not be trusted.
1194
1195   CCM mode
1196       Counter with CBC-MAC, defined in RFC3610 or NIST SP 800-38C.   It  only
1197       works with ciphers having block size 128 bits (like AES).
1198
1199       The new() function at the module level under Crypto.Cipher instantiates
1200       a new CCM cipher object for the relevant base algorithm.  In  the  fol‐
1201       lowing definition, <algorithm> can only be AES today:
1202
1203       Crypto.Cipher.<algorithm>.new(key,  mode,  *, nonce=None, mac_len=None,
1204       msg_len=None, assoc_len=None)
1205              Create a new CCM object, using <algorithm> as the base block ci‐
1206              pher.
1207
1208              Parameters
1209
1210key (bytes) -- the cryptographic key
1211
1212mode -- the constant Crypto.Cipher.<algorithm>.MODE_CCM
1213
1214nonce (bytes) -- the value of the fixed nonce.  It must
1215                       be unique for the combination  message/key.   For  AES,
1216                       its  length  varies from 7 to 13 bytes.  The longer the
1217                       nonce, the smaller the allowed  message  size  (with  a
1218                       nonce of 13 bytes, the message cannot exceed 64KB).  If
1219                       not present, the library  creates  a  11  bytes  random
1220                       nonce (the maximum message size is 8GB).
1221
1222mac_len  (integer) -- the desired length of the MAC tag
1223                       (default if not present: 16 bytes).
1224
1225msg_len (integer) -- pre-declaration of the  length  of
1226                       the  message  to  encipher. If not specified, encrypt()
1227                       and decrypt() can only be called once.
1228
1229assoc_len (integer) -- pre-declaration of the length of
1230                       the  associated  data.  If  not  specified,  some extra
1231                       buffering will take place internally.
1232
1233              Returns
1234                     a CTR cipher object
1235
1236       The cipher object has a read-only attribute nonce.
1237
1238       Example (encryption):
1239
1240          >>> import json
1241          >>> from base64 import b64encode
1242          >>> from Crypto.Cipher import AES
1243          >>> from Crypto.Random import get_random_bytes
1244          >>>
1245          >>> header = b"header"
1246          >>> data = b"secret"
1247          >>> key = get_random_bytes(16)
1248          >>> cipher = AES.new(key, AES.MODE_CCM)
1249          >>> cipher.update(header)
1250          >>> ciphertext, tag = cipher.encrypt_and_digest(data)
1251          >>>
1252          >>> json_k = [ 'nonce', 'header', 'ciphertext', 'tag' ]
1253          >>> json_v = [ b64encode(x).decode('utf-8') for x in cipher.nonce, header, ciphertext, tag ]
1254          >>> result = json.dumps(dict(zip(json_k, json_v)))
1255          >>> print(result)
1256          {"nonce": "p6ffzcKw+6xopVQ=", "header": "aGVhZGVy", "ciphertext": "860kZo/G", "tag": "Ck5YpVCM6fdWnFkFxw8K6A=="}
1257
1258       Example (decryption):
1259
1260          >>> import json
1261          >>> from base64 import b64decode
1262          >>> from Crypto.Cipher import AES
1263          >>>
1264          >>> # We assume that the key was securely shared beforehand
1265          >>> try:
1266          >>>     b64 = json.loads(json_input)
1267          >>>     json_k = [ 'nonce', 'header', 'ciphertext', 'tag' ]
1268          >>>     jv = {k:b64decode(b64[k]) for k in json_k}
1269          >>>
1270          >>>     cipher = AES.new(key, AES.MODE_CCM, nonce=jv['nonce'])
1271          >>>     cipher.update(jv['header'])
1272          >>>     plaintext = cipher.decrypt_and_verify(jv['ciphertext'], jv['tag'])
1273          >>>     print("The message was: " + plaintext)
1274          >>> except ValueError, KeyError:
1275          >>>     print("Incorrect decryption")
1276
1277   EAX mode
1278       An AEAD mode designed for NIST by Bellare, Rogaway, and Wagner in 2003.
1279
1280       The new() function at the module level under Crypto.Cipher instantiates
1281       a new EAX cipher object for the relevant base algorithm.
1282
1283       Crypto.Cipher.<algorithm>.new(key, mode, *, nonce=None, mac_len=None)
1284              Create a new EAX object, using <algorithm> as the base block ci‐
1285              pher.
1286
1287              Parameters
1288
1289key (bytes) -- the cryptographic key
1290
1291mode -- the constant Crypto.Cipher.<algorithm>.MODE_EAX
1292
1293nonce (bytes) -- the value of the fixed nonce.  It must
1294                       be  unique  for  the  combination  message/key.  If not
1295                       present, the library creates a random nonce  (16  bytes
1296                       long for AES).
1297
1298mac_len  (integer) -- the desired length of the MAC tag
1299                       (default if not present: the cipher's  block  size,  16
1300                       bytes for AES).
1301
1302              Returns
1303                     an EAX cipher object
1304
1305       The cipher object has a read-only attribute nonce.
1306
1307       Example (encryption):
1308
1309          >>> import json
1310          >>> from base64 import b64encode
1311          >>> from Crypto.Cipher import AES
1312          >>> from Crypto.Random import get_random_bytes
1313          >>>
1314          >>> header = b"header"
1315          >>> data = b"secret"
1316          >>> key = get_random_bytes(16)
1317          >>> cipher = AES.new(key, AES.MODE_EAX)
1318          >>> cipher.update(header)
1319          >>> ciphertext, tag = cipher.encrypt_and_digest(data)
1320          >>>
1321          >>> json_k = [ 'nonce', 'header', 'ciphertext', 'tag' ]
1322          >>> json_v = [ b64encode(x).decode('utf-8') for x in cipher.nonce, header, ciphertext, tag ]
1323          >>> result = json.dumps(dict(zip(json_k, json_v)))
1324          >>> print(result)
1325          {"nonce": "CSIJ+e8KP7HJo+hC4RXIyQ==", "header": "aGVhZGVy", "ciphertext": "9YYjuAn6", "tag": "kXHrs9ZwYmjDkmfEJx7Clg=="}
1326
1327       Example (decryption):
1328
1329          >>> import json
1330          >>> from base64 import b64decode
1331          >>> from Crypto.Cipher import AES
1332          >>>
1333          >>> # We assume that the key was securely shared beforehand
1334          >>> try:
1335          >>>     b64 = json.loads(json_input)
1336          >>>     json_k = [ 'nonce', 'header', 'ciphertext', 'tag' ]
1337          >>>     jv = {k:b64decode(b64[k]) for k in json_k}
1338          >>>
1339          >>>     cipher = AES.new(key, AES.MODE_EAX, nonce=jv['nonce'])
1340          >>>     cipher.update(jv['header'])
1341          >>>     plaintext = cipher.decrypt_and_verify(jv['ciphertext'], jv['tag'])
1342          >>>     print("The message was: " + plaintext)
1343          >>> except ValueError, KeyError:
1344          >>>     print("Incorrect decryption")
1345
1346   GCM mode
1347       Galois/Counter Mode, defined in NIST SP 800-38D.  It only works in com‐
1348       bination with a 128 bits cipher like AES.
1349
1350       The new() function at the module level under Crypto.Cipher instantiates
1351       a new GCM cipher object for the relevant base algorithm.
1352
1353       Crypto.Cipher.<algorithm>.new(key, mode, *, nonce=None, mac_len=None)
1354              Create a new GCM object, using <algorithm> as the base block ci‐
1355              pher.
1356
1357              Parameters
1358
1359key (bytes) -- the cryptographic key
1360
1361mode -- the constant Crypto.Cipher.<algorithm>.MODE_GCM
1362
1363nonce (bytes) -- the value of the fixed nonce.  It must
1364                       be  unique  for  the  combination  message/key.  If not
1365                       present, the library creates a random nonce  (16  bytes
1366                       long for AES).
1367
1368mac_len (integer) -- the desired length of the MAC tag,
1369                       from 4 to 16 bytes (default: 16).
1370
1371              Returns
1372                     a GCM cipher object
1373
1374       The cipher object has a read-only attribute nonce.
1375
1376       Example (encryption):
1377
1378          >>> import json
1379          >>> from base64 import b64encode
1380          >>> from Crypto.Cipher import AES
1381          >>> from Crypto.Random import get_random_bytes
1382          >>>
1383          >>> header = b"header"
1384          >>> data = b"secret"
1385          >>> key = get_random_bytes(16)
1386          >>> cipher = AES.new(key, AES.MODE_GCM)
1387          >>> cipher.update(header)
1388          >>> ciphertext, tag = cipher.encrypt_and_digest(data)
1389          >>>
1390          >>> json_k = [ 'nonce', 'header', 'ciphertext', 'tag' ]
1391          >>> json_v = [ b64encode(x).decode('utf-8') for x in [cipher.nonce, header, ciphertext, tag ]]
1392          >>> result = json.dumps(dict(zip(json_k, json_v)))
1393          >>> print(result)
1394          {"nonce": "DpOK8NIOuSOQlTq+BphKWw==", "header": "aGVhZGVy", "ciphertext": "CZVqyacc", "tag": "B2tBgICbyw+Wji9KpLVa8w=="}
1395
1396       Example (decryption):
1397
1398          >>> import json
1399          >>> from base64 import b64decode
1400          >>> from Crypto.Cipher import AES
1401          >>> from Crypto.Util.Padding import unpad
1402          >>>
1403          >>> # We assume that the key was securely shared beforehand
1404          >>> try:
1405          >>>     b64 = json.loads(json_input)
1406          >>>     json_k = [ 'nonce', 'header', 'ciphertext', 'tag' ]
1407          >>>     jv = {k:b64decode(b64[k]) for k in json_k}
1408          >>>
1409          >>>     cipher = AES.new(key, AES.MODE_GCM, nonce=jv['nonce'])
1410          >>>     cipher.update(jv['header'])
1411          >>>     plaintext = cipher.decrypt_and_verify(jv['ciphertext'], jv['tag'])
1412          >>>     print("The message was: " + plaintext)
1413          >>> except ValueError, KeyError:
1414          >>>     print("Incorrect decryption")
1415
1416       NOTE:
1417          GCM is most commonly used with 96-bit  (12-byte)  nonces,  which  is
1418          also the length recommended by NIST SP 800-38D.
1419
1420          If  interoperability is important, one should take into account that
1421          the library default of a 128-bit random nonce may  not  be  (easily)
1422          supported  by  other implementations.  A 96-bit nonce can be explic‐
1423          itly generated for a new encryption cipher:
1424
1425              >>> key = get_random_bytes(16)
1426              >>> nonce = get_random_bytes(12)
1427              >>> cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
1428
1429   SIV mode
1430       Synthetic Initialization Vector (SIV), defined  in  RFC5297.   It  only
1431       works with ciphers with a block size of 128 bits (like AES).
1432
1433       Although  less  efficient  than other modes, SIV is nonce misuse-resis‐
1434       tant: accidental reuse of the nonce does not jeopardize the security as
1435       it  happens  with CCM or GCM.  As a matter of fact, operating without a
1436       nonce is not an error per se: the cipher simply becomes  deterministic.
1437       In  other  words, a message gets always encrypted into the same cipher‐
1438       text.
1439
1440       The new() function at the module level under Crypto.Cipher instantiates
1441       a new SIV cipher object for the relevant base algorithm.
1442
1443       Crypto.Cipher.<algorithm>.new(key, mode, *, nonce=None)
1444              Create a new SIV object, using <algorithm> as the base block ci‐
1445              pher.
1446
1447              Parameters
1448
1449key (bytes) -- the cryptographic key; it must be  twice
1450                       the  size  of the key required by the underlying cipher
1451                       (e.g. 32 bytes for AES-128).
1452
1453mode -- the constant Crypto.Cipher.<algorithm>.MODE_SIV
1454
1455nonce (bytes) -- the value of the fixed nonce.  It must
1456                       be  unique  for  the  combination  message/key.  If not
1457                       present, the encryption will be deterministic.
1458
1459              Returns
1460                     a SIV cipher object
1461
1462       If the nonce parameter was provided to new(), the resulting cipher  ob‐
1463       ject has a read-only attribute nonce.
1464
1465       Example (encryption):
1466
1467          >>> import json
1468          >>> from base64 import b64encode
1469          >>> from Crypto.Cipher import AES
1470          >>> from Crypto.Random import get_random_bytes
1471          >>>
1472          >>> header = b"header"
1473          >>> data = b"secret"
1474          >>> key = get_random_bytes(16 * 2)
1475          >>> nonce = get_random_bytes(16)
1476          >>> cipher = AES.new(key, AES.MODE_SIV, nonce=nonce)    # Without nonce, the encryption
1477          >>>                                                     # becomes deterministic
1478          >>> cipher.update(header)
1479          >>> ciphertext, tag = cipher.encrypt_and_digest(data)
1480          >>>
1481          >>> json_k = [ 'nonce', 'header', 'ciphertext', 'tag' ]
1482          >>> json_v = [ b64encode(x).decode('utf-8') for x in nonce, header, ciphertext, tag ]
1483          >>> result = json.dumps(dict(zip(json_k, json_v)))
1484          >>> print(result)
1485          {"nonce": "zMiifAVvDpMS8hnGK/z+iw==", "header": "aGVhZGVy", "ciphertext": "Q7lReEAF", "tag": "KgdnBVbCee6B/wGmMf/wQA=="}
1486
1487       Example (decryption):
1488
1489          >>> import json
1490          >>> from base64 import b64decode
1491          >>> from Crypto.Cipher import AES
1492          >>>
1493          >>> # We assume that the key was securely shared beforehand
1494          >>> try:
1495          >>>     b64 = json.loads(json_input)
1496          >>>     json_k = [ 'nonce', 'header', 'ciphertext', 'tag' ]
1497          >>>     jv = {k:b64decode(b64[k]) for k in json_k}
1498          >>>
1499          >>>     cipher = AES.new(key, AES.MODE_SIV, nonce=jv['nonce'])
1500          >>>     cipher.update(jv['header'])
1501          >>>     plaintext = cipher.decrypt_and_verify(jv['ciphertext'], jv['tag'])
1502          >>>     print("The message was: " + plaintext)
1503          >>> except ValueError, KeyError:
1504          >>>     print("Incorrect decryption")
1505
1506       One  side-effect  is that encryption (or decryption) must take place in
1507       one go with the method encrypt_and_digest() (or  decrypt_and_verify()).
1508       You cannot use encrypt() or decrypt(). The state diagram is therefore:
1509         [image] State diagram for the SIV cipher mode.UNINDENT
1510
1511         The  length  of  the key passed to new() must be twice as required by
1512         the underlying block cipher (e.g. 32 bytes for AES-128).
1513
1514         Each call to the method update() consumes an full piece of associated
1515         data.  That is, the sequence:
1516
1517          >>> siv_cipher.update(b"builtin")
1518          >>> siv_cipher.update(b"securely")
1519
1520       is not equivalent to:
1521
1522          >>> siv_cipher.update(b"built")
1523          >>> siv_cipher.update(b"insecurely")
1524
1525   OCB mode
1526       Offset  CodeBook  mode,  a  cipher designed by Rogaway and specified in
1527       RFC7253 (more specifically, this module implements  the  last  variant,
1528       OCB3).  It only works in combination with a 128 bits cipher like AES.
1529
1530       OCB is patented in USA but free licenses exist for software implementa‐
1531       tions meant for non-military purposes and open source.
1532
1533       The new() function at the module level under Crypto.Cipher instantiates
1534       a new OCB cipher object for the relevant base algorithm.
1535
1536       Crypto.Cipher.<algorithm>.new(key, mode, *, nonce=None, mac_len=None)
1537              Create a new OCB object, using <algorithm> as the base block ci‐
1538              pher.
1539
1540              Parameters
1541
1542key (bytes) -- the cryptographic key
1543
1544mode -- the constant Crypto.Cipher.<algorithm>.MODE_OCB
1545
1546nonce (bytes) -- the value of  the  fixed  nonce,  wuth
1547                       length  between  1 and 15 bytes.  It must be unique for
1548                       the combination message/key.  If not present,  the  li‐
1549                       brary creates a 15 bytes random nonce.
1550
1551mac_len  (integer) -- the desired length of the MAC tag
1552                       (default if not present: 16 bytes).
1553
1554              Returns
1555                     an OCB cipher object
1556
1557       The cipher object has a read-only attribute nonce.
1558
1559       Example (encryption):
1560
1561          >>> import json
1562          >>> from base64 import b64encode
1563          >>> from Crypto.Cipher import AES
1564          >>> from Crypto.Random import get_random_bytes
1565          >>>
1566          >>> header = b"header"
1567          >>> data = b"secret"
1568          >>> key = get_random_bytes(16)
1569          >>> cipher = AES.new(key, AES.MODE_OCB)
1570          >>> cipher.update(header)
1571          >>> ciphertext, tag = cipher.encrypt_and_digest(data)
1572          >>>
1573          >>> json_k = [ 'nonce', 'header', 'ciphertext', 'tag' ]
1574          >>> json_v = [ b64encode(x).decode('utf-8') for x in cipher.nonce, header, ciphertext, tag ]
1575          >>> result = json.dumps(dict(zip(json_k, json_v)))
1576          >>> print(result)
1577          {"nonce": "I7E6PKxHNYo2i9sz8W98", "header": "aGVhZGVy", "ciphertext": "nYJnJ8jC", "tag": "0UbFcmO9lqGknCIDWRLALA=="}
1578
1579       Example (decryption):
1580
1581          >>> import json
1582          >>> from base64 import b64decode
1583          >>> from Crypto.Cipher import AES
1584          >>>
1585          >>> # We assume that the key was securely shared beforehand
1586          >>> try:
1587          >>>     b64 = json.loads(json_input)
1588          >>>     json_k = [ 'nonce', 'header', 'ciphertext', 'tag' ]
1589          >>>     jv = {k:b64decode(b64[k]) for k in json_k}
1590          >>>
1591          >>>     cipher = AES.new(key, AES.MODE_OCB, nonce=jv['nonce'])
1592          >>>     cipher.update(jv['header'])
1593          >>>     plaintext = cipher.decrypt_and_verify(jv['ciphertext'], jv['tag'])
1594          >>>     print("The message was: " + plaintext)
1595          >>> except ValueError, KeyError:
1596          >>>     print("Incorrect decryption")
1597
1598   Legacy ciphers
1599       A number of ciphers are implemented in this library purely for backward
1600       compatibility  purposes.   They are deprecated or even fully broken and
1601       should not be used in new designs.
1602
1603       • des and des3 (block ciphers)
1604
1605       • arc2 (block cipher)
1606
1607       • arc4 (stream cipher)
1608
1609       • blowfish (block cipher)
1610
1611       • cast (block cipher)
1612
1613       • pkcs1_v1_5 (asymmetric cipher)
1614
1615   Crypto.Signature package
1616       The Crypto.Signature package contains algorithms for performing digital
1617       signatures, used to guarantee integrity and non-repudiation.
1618
1619       Digital signatures are based on public key cryptography: the party that
1620       signs a message holds the private key, the one that verifies the signa‐
1621       ture holds the public key.
1622
1623   Signing a message
1624       1. Instantiate  a  new signer object for the desired algorithm, for in‐
1625          stance with Crypto.Signature.pkcs1_15.new().  The first parameter is
1626          the  key object (private key) obtained via the Crypto.PublicKey mod‐
1627          ule.
1628
1629       2. Instantiate  a  cryptographic  hash  object,   for   instance   with
1630          Crypto.Hash.SHA384.new().   Then,  process  the message with its up‐
1631          date() method.
1632
1633       3. Invoke the sign() method on the signer with the hash object  as  pa‐
1634          rameter.   The  output  is  the  signature  of  the  message (a byte
1635          string).
1636
1637   Verifying a signature
1638       1. Instantiate a new verifier object for the desired algorithm, for in‐
1639          stance with Crypto.Signature.pkcs1_15.new().  The first parameter is
1640          the key object (public key) obtained via the  Crypto.PublicKey  mod‐
1641          ule.
1642
1643       2. Instantiate   a   cryptographic   hash  object,  for  instance  with
1644          Crypto.Hash.SHA384.new().  Then, process the message  with  its  up‐
1645          date() method.
1646
1647       3. Invoke the verify() method on the verifier, with the hash object and
1648          the incoming signature as parameters.  If the message is not authen‐
1649          tic, an ValueError is raised.
1650
1651   Available mechanisms
1652       • pkcs1_v1_5
1653
1654       • pkcs1_pss
1655
1656       • dsa
1657
1658   Crypto.Hash package
1659       Cryptographic  hash  functions  take arbitrary binary strings as input,
1660       and produce a random-like fixed-length output (called  digest  or  hash
1661       value).
1662
1663       It is practically infeasible to derive the original input data from the
1664       digest. In other words, the  cryptographic  hash  function  is  one-way
1665       (pre-image resistance).
1666
1667       Given  the  digest of one message, it is also practically infeasible to
1668       find another message (second pre-image) with the same digest (weak col‐
1669       lision resistance).
1670
1671       Finally,  it is infeasible to find two arbitrary messages with the same
1672       digest (strong collision resistance).
1673
1674       Regardless of the hash algorithm, an n bits long digest is at  most  as
1675       secure  as  a  symmetric  encryption  algorithm keyed with  n/2 bits (‐
1676       birthday attack).
1677
1678       Hash functions can be simply used as integrity checks.  In  combination
1679       with a public-key algorithm, you can implement a digital signature.
1680
1681   API principles
1682         [image] Generic state diagram for a hash object.UNINDENT
1683
1684         Every  time you want to hash a message, you have to create a new hash
1685         object with the new() function in the relevant algorithm module (e.g.
1686         Crypto.Hash.SHA256.new()).
1687
1688         A first piece of message to hash can be passed to new() with the data
1689         parameter:
1690
1691          >> from Crypto.Hash import SHA256
1692          >>
1693          >> hash_object = SHA256.new(data=b'First')
1694
1695       NOTE:
1696          You can only hash byte strings or byte arrays (no Python  2  Unicode
1697          strings or Python 3 strings).
1698
1699       Afterwards,  the  method update() can be invoked any number of times as
1700       necessary, with other pieces of message:
1701
1702          >>> hash_object.update(b'Second')
1703          >>> hash_object.update(b'Third')
1704
1705       The two steps above are equivalent to:
1706
1707          >>> hash_object.update(b'SecondThird')
1708
1709       At the end, the digest can be retrieved with the  methods  digest()  or
1710       hexdigest():
1711
1712          >>> print(hash_object.digest())
1713          b'}\x96\xfd@\xb2$?O\xca\xc1a\x10\x15\x8c\x94\xe4\xb4\x085"\xd5"\xa8\xa4C\x9e+\x00\x859\xc7A'
1714          >>> print(hash_object.hexdigest())
1715          7d96fd40b2243f4fcac16110158c94e4b4083522d522a8a4439e2b008539c741
1716
1717   Attributes of hash objects
1718       Every hash object has the following attributes:
1719
1720                     ┌────────────┬────────────────────────────┐
1721                     │Attribute   │ Description                │
1722                     ├────────────┼────────────────────────────┤
1723                     │digest_size │ Size   of  the  digest  in │
1724                     │            │ bytes, that is, the output │
1725                     │            │ of  the  digest()  method. │
1726                     │            │ It does not exist for hash │
1727                     │            │ functions   with  variable │
1728                     │            │ digest  output  (such   as │
1729                     │            │ Crypto.Hash.SHAKE128).     │
1730                     │            │ This is also a module  at‐ │
1731                     │            │ tribute.                   │
1732                     ├────────────┼────────────────────────────┤
1733                     │block_size  │ The  size  of  the message │
1734                     │            │ block in bytes,  input  to │
1735                     │            │ the  compression function. │
1736                     │            │ Only applicable for  algo‐ │
1737                     │            │ rithms    based   on   the │
1738                     │            │ Merkle-Damgard   construc‐ │
1739                     │            │ tion                 (e.g. │
1740                     │            │ Crypto.Hash.SHA256).  This │
1741                     │            │ is  also  a  module attri‐ │
1742                     │            │ bute.                      │
1743                     ├────────────┼────────────────────────────┤
1744                     │oid         │ A string with  the  dotted │
1745                     │            │ representation    of   the │
1746                     │            │ ASN.1 OID assigned to  the │
1747                     │            │ hash algorithm.            │
1748                     └────────────┴────────────────────────────┘
1749
1750   Modern hash algorithms
1751       • SHA-2 family
1752
1753            • sha224
1754
1755            • sha256
1756
1757            • sha384
1758
1759            • sha512
1760
1761       • SHA-3 family
1762
1763            • sha3_224
1764
1765            • sha3_256
1766
1767            • sha3_384
1768
1769            • sha3_512
1770
1771       • BLAKE2
1772
1773            • blake2s
1774
1775            • blake2b
1776
1777   Extensible-Output Functions (XOF)
1778       • SHAKE (in the SHA-3 family)
1779
1780            • shake128
1781
1782            • shake256
1783
1784   Message Authentication Code (MAC) algorithms
1785       • hmac
1786
1787       • cmac
1788
1789       • poly1305
1790
1791   Historic hash algorithms
1792       The following algorithms should not be used in new designs:
1793
1794       • sha1
1795
1796       • md2
1797
1798       • md5
1799
1800       • ripemd160
1801
1802       • keccak
1803
1804   Crypto.PublicKey package
1805       In  a  public key cryptography system, senders and receivers do not use
1806       the same key.  Instead, the system defines a key pair, with one of  the
1807       keys being confidential (private) and the other not (public).
1808
1809                   ┌───────────┬───────────────┬──────────────────┐
1810                   │Algorithm  │ Sender uses.. │ Receiver uses... │
1811                   ├───────────┼───────────────┼──────────────────┤
1812                   │Encryption │ Public key    │ Private key      │
1813                   ├───────────┼───────────────┼──────────────────┤
1814                   │Signature  │ Private key   │ Public key       │
1815                   └───────────┴───────────────┴──────────────────┘
1816
1817       Unlike  keys meant for symmetric cipher algorithms (typically just ran‐
1818       dom bit strings), keys for public key  algorithms  have  very  specific
1819       properties.  This  module  collects  all methods to generate, validate,
1820       store and retrieve public keys.
1821
1822   API principles
1823       Asymmetric keys are represented by Python objects. Each object  can  be
1824       either  a  private key or a public key (the method has_private() can be
1825       used to distinguish them).
1826
1827       A key object can be created in four ways:
1828
1829       1. generate() at the  module  level  (e.g.  Crypto.PublicKey.RSA.gener‐
1830          ate()).  The key is randomly created each time.
1831
1832       2. import_key()  at  the  module  level  (e.g. Crypto.PublicKey.RSA.im‐
1833          port_key()).  The key is loaded from memory.
1834
1835       3. construct() at  the  module  level  (e.g.  Crypto.PublicKey.RSA.con‐
1836          struct()).  The key will be built from a set of sub-components.
1837
1838       4. publickey()     at    the    object    level    (e.g.    Crypto.Pub‐
1839          licKey.RSA.RsaKey.publickey()).  The key  will  be  the  public  key
1840          matching the given object.
1841
1842       A key object can be serialized via its export_key() method.
1843
1844       Keys  objects  can  be compared via the usual operators == and != (note
1845       that the two halves of the same key, private and public, are considered
1846       as two different keys).
1847
1848   Available key types
1849   RSA
1850       RSA  is the most widespread and used public key algorithm. Its security
1851       is based on the difficulty of factoring large integers.  The  algorithm
1852       has  withstood attacks for more than 30 years, and it is therefore con‐
1853       sidered reasonably secure for new designs.
1854
1855       The algorithm can be used for both confidentiality (encryption) and au‐
1856       thentication  (digital  signature). It is worth noting that signing and
1857       decryption are significantly slower than verification and encryption.
1858
1859       The cryptographic strength is primarily linked to the length of the RSA
1860       modulus n.  In 2017, a sufficient length is deemed to be 2048 bits. For
1861       more information, see the most recent ECRYPT report.
1862
1863       Both RSA ciphertexts and RSA signatures are as large as the RSA modulus
1864       n (256 bytes if n is 2048 bit long).
1865
1866       The  module Crypto.PublicKey.RSA provides facilities for generating new
1867       RSA keys, reconstructing them from known  components,  exporting  them,
1868       and importing them.
1869
1870       As  an example, this is how you generate a new RSA key pair, save it in
1871       a file called mykey.pem, and then read it back:
1872
1873          >>> from Crypto.PublicKey import RSA
1874          >>>
1875          >>> key = RSA.generate(2048)
1876          >>> f = open('mykey.pem','wb')
1877          >>> f.write(key.export_key('PEM'))
1878          >>> f.close()
1879          ...
1880          >>> f = open('mykey.pem','r')
1881          >>> key = RSA.import_key(f.read())
1882
1883       class Crypto.PublicKey.RSA.RsaKey(**kwargs)
1884              Class defining an actual RSA key.  Do not instantiate  directly.
1885              Use generate(), construct() or import_key() instead.
1886
1887              Variables
1888
1889n (integer) -- RSA modulus
1890
1891e (integer) -- RSA public exponent
1892
1893d (integer) -- RSA private exponent
1894
1895p (integer) -- First factor of the RSA modulus
1896
1897q (integer) -- Second factor of the RSA modulus
1898
1899u -- Chinese remainder component (p^{-1} \text{mod } q)
1900
1901              Undocumented
1902                     exportKey, publickey
1903
1904              exportKey(format='PEM',    passphrase=None,    pkcs=1,   protec‐
1905              tion=None, randfunc=None)
1906                     Export this RSA key.
1907
1908                     Parameters
1909
1910format (string) --
1911
1912                              The format to use for wrapping the key:
1913
1914'PEM'. (Default) Text encoding, done according
1915                                to RFC1421/RFC1423.
1916
1917'DER'. Binary encoding.
1918
1919'OpenSSH'. Textual encoding, done according to
1920                                OpenSSH specification.  Only suitable for pub‐
1921                                lic keys (not private keys).
1922
1923
1924passphrase  (string)  -- (For private keys only)
1925                              The pass phrase used for protecting the output.
1926
1927pkcs (integer) --
1928
1929                              (For private keys only) The ASN.1  structure  to
1930                              use  for  serializing the key. Note that even in
1931                              case of PEM encoding, there is  an  inner  ASN.1
1932                              DER structure.
1933
1934                              With  pkcs=1  (default),  the private key is en‐
1935                              coded in  a  simple  PKCS#1  structure  (RSAPri‐
1936                              vateKey).
1937
1938                              With  pkcs=8,  the  private  key is encoded in a
1939                              PKCS#8 structure (PrivateKeyInfo).
1940
1941                              NOTE:
1942                                 This parameter is ignored for a  public  key.
1943                                 For DER and PEM, an ASN.1 DER SubjectPublicK‐
1944                                 eyInfo structure is always used.
1945
1946
1947protection (string) --
1948
1949                              (For private keys only) The encryption scheme to
1950                              use for protecting the private key.
1951
1952                              If  None (default), the behavior depends on for‐
1953                              mat:
1954
1955                              • For   'DER',    the    PBKDF2WithHMAC-SHA1And‐
1956                                DES-EDE3-CBC scheme is used. The following op‐
1957                                erations are performed:
1958
1959                                   1. A 16 byte Triple DES key is derived from
1960                                      the   passphrase   using   Crypto.Proto‐
1961                                      col.KDF.PBKDF2() with 8 bytes salt,  and
1962                                      1 000 iterations of Crypto.Hash.HMAC.
1963
1964                                   2. The private key is encrypted using CBC.
1965
1966                                   3. The  encrypted  key is encoded according
1967                                      to PKCS#8.
1968
1969                              • For 'PEM', the obsolete PEM encryption  scheme
1970                                is  used.   It is based on MD5 for key deriva‐
1971                                tion, and Triple DES for encryption.
1972
1973                              Specifying a value for protection is only  mean‐
1974                              ingful  for PKCS#8 (that is, pkcs=8) and only if
1975                              a pass phrase is present too.
1976
1977                              The supported schemes for PKCS#8 are  listed  in
1978                              the Crypto.IO.PKCS8 module (see wrap_algo param‐
1979                              eter).
1980
1981
1982randfunc (callable) -- A function that  provides
1983                              random  bytes.  Only used for PEM encoding.  The
1984                              default is Crypto.Random.get_random_bytes().
1985
1986                     Returns
1987                            the encoded key
1988
1989                     Return type
1990                            byte string
1991
1992                     Raises ValueError -- when the format is unknown  or  when
1993                            you try to encrypt a private
1994                                key with DER format and PKCS#1.
1995
1996                     WARNING:
1997                        If  you  don't  provide a pass phrase, the private key
1998                        will be exported in the clear!
1999
2000              export_key(format='PEM',   passphrase=None,   pkcs=1,    protec‐
2001              tion=None, randfunc=None)
2002                     Export this RSA key.
2003
2004                     Parameters
2005
2006format (string) --
2007
2008                              The format to use for wrapping the key:
2009
2010'PEM'. (Default) Text encoding, done according
2011                                to RFC1421/RFC1423.
2012
2013'DER'. Binary encoding.
2014
2015'OpenSSH'. Textual encoding, done according to
2016                                OpenSSH specification.  Only suitable for pub‐
2017                                lic keys (not private keys).
2018
2019
2020passphrase (string) -- (For private  keys  only)
2021                              The pass phrase used for protecting the output.
2022
2023pkcs (integer) --
2024
2025                              (For  private  keys only) The ASN.1 structure to
2026                              use for serializing the key. Note that  even  in
2027                              case  of  PEM  encoding, there is an inner ASN.1
2028                              DER structure.
2029
2030                              With pkcs=1 (default), the private  key  is  en‐
2031                              coded  in  a  simple  PKCS#1  structure (RSAPri‐
2032                              vateKey).
2033
2034                              With pkcs=8, the private key  is  encoded  in  a
2035                              PKCS#8 structure (PrivateKeyInfo).
2036
2037                              NOTE:
2038                                 This  parameter  is ignored for a public key.
2039                                 For DER and PEM, an ASN.1 DER SubjectPublicK‐
2040                                 eyInfo structure is always used.
2041
2042
2043protection (string) --
2044
2045                              (For private keys only) The encryption scheme to
2046                              use for protecting the private key.
2047
2048                              If None (default), the behavior depends on  for‐
2049                              mat:
2050
2051                              • For    'DER',    the   PBKDF2WithHMAC-SHA1And‐
2052                                DES-EDE3-CBC scheme is used. The following op‐
2053                                erations are performed:
2054
2055                                   1. A 16 byte Triple DES key is derived from
2056                                      the   passphrase   using   Crypto.Proto‐
2057                                      col.KDF.PBKDF2()  with 8 bytes salt, and
2058                                      1 000 iterations of Crypto.Hash.HMAC.
2059
2060                                   2. The private key is encrypted using CBC.
2061
2062                                   3. The encrypted key is  encoded  according
2063                                      to PKCS#8.
2064
2065                              • For  'PEM', the obsolete PEM encryption scheme
2066                                is used.  It is based on MD5 for  key  deriva‐
2067                                tion, and Triple DES for encryption.
2068
2069                              Specifying  a value for protection is only mean‐
2070                              ingful for PKCS#8 (that is, pkcs=8) and only  if
2071                              a pass phrase is present too.
2072
2073                              The  supported  schemes for PKCS#8 are listed in
2074                              the Crypto.IO.PKCS8 module (see wrap_algo param‐
2075                              eter).
2076
2077
2078randfunc  (callable) -- A function that provides
2079                              random bytes. Only used for PEM  encoding.   The
2080                              default is Crypto.Random.get_random_bytes().
2081
2082                     Returns
2083                            the encoded key
2084
2085                     Return type
2086                            byte string
2087
2088                     Raises ValueError  --  when the format is unknown or when
2089                            you try to encrypt a private
2090                                key with DER format and PKCS#1.
2091
2092                     WARNING:
2093                        If you don't provide a pass phrase,  the  private  key
2094                        will be exported in the clear!
2095
2096              has_private()
2097                     Whether this is an RSA private key
2098
2099              public_key()
2100                     A matching RSA public key.
2101
2102                     Returns
2103                            a new RsaKey object
2104
2105              publickey()
2106                     A matching RSA public key.
2107
2108                     Returns
2109                            a new RsaKey object
2110
2111              size_in_bits()
2112                     Size of the RSA modulus in bits
2113
2114              size_in_bytes()
2115                     The minimal amount of bytes that can hold the RSA modulus
2116
2117       Crypto.PublicKey.RSA.construct(rsa_components, consistency_check=True)
2118              Construct an RSA key from a tuple of valid RSA components.
2119
2120              The modulus n must be the product of two primes.  The public ex‐
2121              ponent e must be odd and larger than 1.
2122
2123              In case of a private key, the following equations must apply:
2124
2125                                       \begin{align}
2126              p*q &= n \\ e*d &\equiv 1 ( \text{mod lcm} [(p-1)(q-1)]) \\  p*u
2127              &\equiv 1 ( \text{mod } q) \end{align}
2128
2129              Parameters
2130
2131rsa_components (tuple) --
2132
2133                       A tuple of integers, with at least 2 and no more than 6
2134                       items. The items come in the following order:
2135
2136                       1. RSA modulus n.
2137
2138                       2. Public exponent e.
2139
2140                       3. Private exponent d.  Only required  if  the  key  is
2141                          private.
2142
2143                       4. First factor of n (p).  Optional, but the other fac‐
2144                          tor q must also be present.
2145
2146                       5. Second factor of n (q). Optional.
2147
2148                       6. CRT coefficient q, that is p^{-1} \text{mod }q.  Op‐
2149                          tional.
2150
2151
2152consistency_check  (boolean)  --  If  True, the library
2153                       will verify that the  provided  components  fulfil  the
2154                       main RSA properties.
2155
2156              Raises ValueError  -- when the key being imported fails the most
2157                     basic RSA validity checks.
2158
2159              Returns: An RSA key object (RsaKey).
2160
2161       Crypto.PublicKey.RSA.generate(bits, randfunc=None, e=65537)
2162              Create a new RSA key pair.
2163
2164              The algorithm closely follows NIST FIPS 186-4  in  its  sections
2165              B.3.1  and  B.3.3.  The modulus is the product of two non-strong
2166              probable  primes.   Each  prime  passes  a  suitable  number  of
2167              Miller-Rabin tests with random bases and a single Lucas test.
2168
2169              Parameters
2170
2171bits  (integer) -- Key length, or size (in bits) of the
2172                       RSA modulus.  It must be at least  1024,  but  2048  is
2173                       recommended.  The FIPS standard only defines 1024, 2048
2174                       and 3072.
2175
2176randfunc (callable) --  Function  that  returns  random
2177                       bytes.     The    default   is   Crypto.Random.get_ran‐
2178                       dom_bytes().
2179
2180e (integer) -- Public RSA exponent. It must be  an  odd
2181                       positive  integer.  It is typically a small number with
2182                       very few ones in its binary representation.   The  FIPS
2183                       standard  requires  the  public exponent to be at least
2184                       65537 (the default).
2185
2186              Returns: an RSA key object (RsaKey, with private key).
2187
2188       Crypto.PublicKey.RSA.import_key(extern_key, passphrase=None)
2189              Import an RSA key (public or private).
2190
2191              Parameters
2192
2193extern_key (string or byte string) --
2194
2195                       The RSA key to import.
2196
2197                       The following formats are supported for an  RSA  public
2198                       key:
2199
2200                       • X.509 certificate (binary or PEM format)
2201
2202                       • X.509  subjectPublicKeyInfo  DER  SEQUENCE (binary or
2203                         PEM encoding)
2204
2205PKCS#1 RSAPublicKey DER SEQUENCE (binary or  PEM  en‐
2206                         coding)
2207
2208                       • An OpenSSH line (e.g. the content of ~/.ssh/id_ecdsa,
2209                         ASCII)
2210
2211                       The following formats are supported for an RSA  private
2212                       key:
2213
2214                       • PKCS#1  RSAPrivateKey DER SEQUENCE (binary or PEM en‐
2215                         coding)
2216
2217PKCS#8 PrivateKeyInfo or EncryptedPrivateKeyInfo  DER
2218                         SEQUENCE (binary or PEM encoding)
2219
2220                       • OpenSSH (text format, introduced in OpenSSH 6.5)
2221
2222                       For  details  about  the  PEM  encoding,  see RFC1421/‐
2223                       RFC1423.
2224
2225
2226passphrase (string or byte string) -- For private  keys
2227                       only, the pass phrase that encrypts the key.
2228
2229              Returns: An RSA key object (RsaKey).
2230
2231              Raises ValueError/IndexError/TypeError  --  When  the  given key
2232                     cannot be parsed (possibly because the pass
2233                         phrase is wrong).
2234
2235       Crypto.PublicKey.RSA.oid = '1.2.840.113549.1.1.1'
2236              Object ID for the RSA encryption algorithm. This OID often indi‐
2237              cates  a  generic  RSA  key, even when such key will be actually
2238              used for digital signatures.
2239
2240   DSA
2241       DSA is a widespread public key signature  algorithm.  Its  security  is
2242       based  on the discrete logarithm problem (DLP). Given a cyclic group, a
2243       generator g, and an element h, it is hard to find  an  integer  x  such
2244       that  g^x = h. The problem is believed to be difficult, and it has been
2245       proved such (and therefore secure) for more than 30 years.
2246
2247       The group is actually a sub-group over the integers modulo  p,  with  p
2248       prime.   The  sub-group order is q, which is prime too; it always holds
2249       that (p-1) is a multiple of q.  The cryptographic strength is linked to
2250       the magnitude of p and q.  The signer holds a value x (0<x<q-1) as pri‐
2251       vate key, and its public key (y where y=g^x \text{ mod } p) is distrib‐
2252       uted.
2253
2254       In 2017, a sufficient size is deemed to be 2048 bits for p and 256 bits
2255       for q.  For more information, see the most recent ECRYPT report.
2256
2257       The algorithm can only be used for authentication (digital  signature).
2258       DSA cannot be used for confidentiality (encryption).
2259
2260       The values (p,q,g) are called domain parameters; they are not sensitive
2261       but must be shared by both parties (the signer and the verifier).  Dif‐
2262       ferent  signers  can  share the same domain parameters with no security
2263       concerns.
2264
2265       The DSA signature is twice as big as the size of q (64 bytes  if  q  is
2266       256 bit long).
2267
2268       This  module  provides  facilities  for generating new DSA keys and for
2269       constructing them from known components.
2270
2271       As an example, this is how you generate a new DSA key  pair,  save  the
2272       public  key  in  a  file  called  public_key.pem,  sign a message (with
2273       Crypto.Signature.DSS), and verify it:
2274
2275          >>> from Crypto.PublicKey import DSA
2276          >>> from Crypto.Signature import DSS
2277          >>> from Crypto.Hash import SHA256
2278          >>>
2279          >>> # Create a new DSA key
2280          >>> key = DSA.generate(2048)
2281          >>> f = open("public_key.pem", "w")
2282          >>> f.write(key.publickey().export_key())
2283          >>> f.close()
2284          >>>
2285          >>> # Sign a message
2286          >>> message = b"Hello"
2287          >>> hash_obj = SHA256.new(message)
2288          >>> signer = DSS.new(key, 'fips-186-3')
2289          >>> signature = signer.sign(hash_obj)
2290          >>>
2291          >>> # Load the public key
2292          >>> f = open("public_key.pem", "r")
2293          >>> hash_obj = SHA256.new(message)
2294          >>> pub_key = DSA.import_key(f.read())
2295          >>> verifier = DSS.new(pub_key, 'fips-186-3')
2296          >>>
2297          >>> # Verify the authenticity of the message
2298          >>> try:
2299          >>>     verifier.verify(hash_obj, signature)
2300          >>>     print "The message is authentic."
2301          >>> except ValueError:
2302          >>>     print "The message is not authentic."
2303
2304       class Crypto.PublicKey.DSA.DsaKey(key_dict)
2305              Class defining an actual DSA key.  Do not instantiate  directly.
2306              Use generate(), construct() or import_key() instead.
2307
2308              Variables
2309
2310p (integer) -- DSA modulus
2311
2312q (integer) -- Order of the subgroup
2313
2314g (integer) -- Generator
2315
2316y (integer) -- Public key
2317
2318x (integer) -- Private key
2319
2320              Undocumented
2321                     exportKey, publickey
2322
2323              domain()
2324                     The DSA domain parameters.
2325
2326                     Returns
2327                            tuple : (p,q,g)
2328
2329              exportKey(format='PEM',   pkcs8=None,  passphrase=None,  protec‐
2330              tion=None, randfunc=None)
2331                     Export this DSA key.
2332
2333                     Parameters
2334
2335format (string) --
2336
2337                              The encoding for the output:
2338
2339'PEM'  (default).  ASCII   as   per   RFC1421/
2340                                RFC1423.
2341
2342'DER'. Binary ASN.1 encoding.
2343
2344'OpenSSH'.  ASCII  one-liner  as  per RFC4253.
2345                                Only suitable for public keys, not for private
2346                                keys.
2347
2348
2349passphrase  (string)  --  Private keys only. The
2350                              pass phrase to protect the output.
2351
2352pkcs8 (boolean) -- Private keys  only.  If  True
2353                              (default),  the  key  is encoded with PKCS#8. If
2354                              False,   it   is   encoded   in    the    custom
2355                              OpenSSL/OpenSSH container.
2356
2357protection (string) --
2358
2359                              Only in combination with a pass phrase.  The en‐
2360                              cryption scheme to use to protect the output.
2361
2362                              If pkcs8 takes value True, this  is  the  PKCS#8
2363                              algorithm to use for deriving the secret and en‐
2364                              crypting the private DSA key.   For  a  complete
2365                              list  of  algorithms,  see Crypto.IO.PKCS8.  The
2366                              default is PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC.
2367
2368                              If pkcs8 is False, the obsolete  PEM  encryption
2369                              scheme is used. It is based on MD5 for key deri‐
2370                              vation, and Triple DES for encryption. Parameter
2371                              protection is then ignored.
2372
2373                              The  combination format='DER' and pkcs8=False is
2374                              not allowed if a passphrase is present.
2375
2376
2377randfunc (callable) -- A function  that  returns
2378                              random  bytes.   By  default  it  is Crypto.Ran‐
2379                              dom.get_random_bytes().
2380
2381                     Returns
2382                            the encoded key
2383
2384                     Return type
2385                            byte string
2386
2387                     Raises ValueError -- when the format is unknown  or  when
2388                            you try to encrypt a private
2389                                key with DER format and OpenSSL/OpenSSH.
2390
2391                     WARNING:
2392                        If  you  don't  provide a pass phrase, the private key
2393                        will be exported in the clear!
2394
2395              export_key(format='PEM',  pkcs8=None,  passphrase=None,  protec‐
2396              tion=None, randfunc=None)
2397                     Export this DSA key.
2398
2399                     Parameters
2400
2401format (string) --
2402
2403                              The encoding for the output:
2404
2405'PEM'   (default).   ASCII   as  per  RFC1421/
2406                                RFC1423.
2407
2408'DER'. Binary ASN.1 encoding.
2409
2410'OpenSSH'. ASCII  one-liner  as  per  RFC4253.
2411                                Only suitable for public keys, not for private
2412                                keys.
2413
2414
2415passphrase (string) -- Private  keys  only.  The
2416                              pass phrase to protect the output.
2417
2418pkcs8  (boolean)  --  Private keys only. If True
2419                              (default), the key is encoded  with  PKCS#8.  If
2420                              False,    it    is   encoded   in   the   custom
2421                              OpenSSL/OpenSSH container.
2422
2423protection (string) --
2424
2425                              Only in combination with a pass phrase.  The en‐
2426                              cryption scheme to use to protect the output.
2427
2428                              If  pkcs8  takes  value True, this is the PKCS#8
2429                              algorithm to use for deriving the secret and en‐
2430                              crypting  the  private  DSA key.  For a complete
2431                              list of algorithms,  see  Crypto.IO.PKCS8.   The
2432                              default is PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC.
2433
2434                              If  pkcs8  is False, the obsolete PEM encryption
2435                              scheme is used. It is based on MD5 for key deri‐
2436                              vation, and Triple DES for encryption. Parameter
2437                              protection is then ignored.
2438
2439                              The combination format='DER' and pkcs8=False  is
2440                              not allowed if a passphrase is present.
2441
2442
2443randfunc  (callable)  -- A function that returns
2444                              random bytes.   By  default  it  is  Crypto.Ran‐
2445                              dom.get_random_bytes().
2446
2447                     Returns
2448                            the encoded key
2449
2450                     Return type
2451                            byte string
2452
2453                     Raises ValueError  --  when the format is unknown or when
2454                            you try to encrypt a private
2455                                key with DER format and OpenSSL/OpenSSH.
2456
2457                     WARNING:
2458                        If you don't provide a pass phrase,  the  private  key
2459                        will be exported in the clear!
2460
2461              has_private()
2462                     Whether this is a DSA private key
2463
2464              public_key()
2465                     A matching DSA public key.
2466
2467                     Returns
2468                            a new DsaKey object
2469
2470              publickey()
2471                     A matching DSA public key.
2472
2473                     Returns
2474                            a new DsaKey object
2475
2476       Crypto.PublicKey.DSA.construct(tup, consistency_check=True)
2477              Construct a DSA key from a tuple of valid DSA components.
2478
2479              Parameters
2480
2481tup (tuple) --
2482
2483                       A tuple of long integers, with 4 or 5 items in the fol‐
2484                       lowing order:
2485
2486                          1. Public key (y).
2487
2488                          2. Sub-group generator (g).
2489
2490                          3. Modulus, finite field order (p).
2491
2492                          4. Sub-group order (q).
2493
2494                          5. Private key (x). Optional.
2495
2496
2497consistency_check (boolean) --  If  True,  the  library
2498                       will  verify  that  the  provided components fulfil the
2499                       main DSA properties.
2500
2501              Raises ValueError -- when the key being imported fails the  most
2502                     basic DSA validity checks.
2503
2504              Returns
2505                     a DSA key object
2506
2507              Return type
2508                     DsaKey
2509
2510       Crypto.PublicKey.DSA.generate(bits, randfunc=None, domain=None)
2511              Generate a new DSA key pair.
2512
2513              The  algorithm  follows  Appendix A.1/A.2 and B.1 of FIPS 186-4,
2514              respectively for domain generation and key pair generation.
2515
2516              Parameters
2517
2518bits (integer) -- Key length, or size (in bits) of  the
2519                       DSA modulus p.  It must be 1024, 2048 or 3072.
2520
2521randfunc  (callable)  -- Random number generation func‐
2522                       tion; it accepts a single integer N and return a string
2523                       of  random  data  N  bytes  long.   If  not  specified,
2524                       Crypto.Random.get_random_bytes() is used.
2525
2526domain (tuple) -- The DSA domain parameters p, q and  g
2527                       as a list of 3 integers. Size of p and q must comply to
2528                       FIPS 186-4.  If not specified, the parameters are  cre‐
2529                       ated anew.
2530
2531              Returns
2532                     a new DSA key object
2533
2534              Return type
2535                     DsaKey
2536
2537              Raises ValueError  -- when bits is too little, too big, or not a
2538                     multiple of 64.
2539
2540       Crypto.PublicKey.DSA.import_key(extern_key, passphrase=None)
2541              Import a DSA key.
2542
2543              Parameters
2544
2545extern_key (string or byte string) --
2546
2547                       The DSA key to import.
2548
2549                       The following formats are supported for  a  DSA  public
2550                       key:
2551
2552                       • X.509 certificate (binary DER or PEM)
2553
2554                       • X.509 subjectPublicKeyInfo (binary DER or PEM)
2555
2556                       • OpenSSH (ASCII one-liner, see RFC4253)
2557
2558                       The  following  formats are supported for a DSA private
2559                       key:
2560
2561PKCS#8 PrivateKeyInfo or EncryptedPrivateKeyInfo  DER
2562                         SEQUENCE (binary or PEM)
2563
2564                       • OpenSSL/OpenSSH custom format (binary or PEM)
2565
2566                       For  details  about  the  PEM  encoding,  see RFC1421/‐
2567                       RFC1423.
2568
2569
2570passphrase (string) --
2571
2572                       In case of an encrypted private key, this is  the  pass
2573                       phrase from which the decryption key is derived.
2574
2575                       Encryption  may  be  applied either at the PKCS#8 or at
2576                       the PEM level.
2577
2578
2579              Returns
2580                     a DSA key object
2581
2582              Return type
2583                     DsaKey
2584
2585              Raises ValueError -- when the given key cannot be parsed (possi‐
2586                     bly because
2587                         the pass phrase is wrong).
2588
2589   ECC
2590       ECC  (Elliptic  Curve  Cryptography)  is a modern and efficient type of
2591       public key cryptography.  Its security is based on  the  difficulty  to
2592       solve  discrete  logarithms  on the field defined by specific equations
2593       computed over a curve.
2594
2595       ECC can be used to create digital signatures or to perform  a  key  ex‐
2596       change.
2597
2598       Compared  to  traditional  algorithms  like RSA, an ECC key is signifi‐
2599       cantly smaller at the same security level.  For  instance,  a  3072-bit
2600       RSA  key  takes 768 bytes whereas the equally strong NIST P-256 private
2601       key only takes 32 bytes (that is, 256 bits).
2602
2603       This module provides mechanisms for generating new ECC keys,  exporting
2604       and importing them using widely supported formats like PEM or DER.
2605
2606                      ┌───────────┬────────────────────────────┐
2607                      │Curve      │ Possible identifiers       │
2608                      ├───────────┼────────────────────────────┤
2609                      │NIST P-256 │ 'NIST    P-256',   'p256', │
2610                      │           │ 'P-256',     'prime256v1', │
2611                      │           │ 'secp256r1'                
2612                      ├───────────┼────────────────────────────┤
2613                      │NIST P-384 │ 'NIST    P-384',   'p384', │
2614                      │           │ 'P-384',     'prime384v1', │
2615                      │           │ 'secp384r1'                
2616                      ├───────────┼────────────────────────────┤
2617                      │NIST P-521 │ 'NIST    P-521',   'p521', │
2618                      │           │ 'P-521',     'prime521v1', │
2619                      │           │ 'secp521r1'                
2620                      └───────────┴────────────────────────────┘
2621
2622       For  more  information  about  each  NIST curve see FIPS 186-4, Section
2623       D.1.2.
2624
2625       The following example demonstrates how to generate a new ECC  key,  ex‐
2626       port it, and subsequently reload it back into the application:
2627
2628          >>> from Crypto.PublicKey import ECC
2629          >>>
2630          >>> key = ECC.generate(curve='P-256')
2631          >>>
2632          >>> f = open('myprivatekey.pem','wt')
2633          >>> f.write(key.export_key(format='PEM'))
2634          >>> f.close()
2635          ...
2636          >>> f = open('myprivatekey.pem','rt')
2637          >>> key = ECC.import_key(f.read())
2638
2639       The  ECC  key  can be used to perform or verify ECDSA signatures, using
2640       the module Crypto.Signature.DSS.
2641
2642       class Crypto.PublicKey.ECC.EccKey(**kwargs)
2643              Class defining an ECC key.  Do not  instantiate  directly.   Use
2644              generate(), construct() or import_key() instead.
2645
2646              Variables
2647
2648curve  (string)  --  The  name of the ECC as defined in
2649                       curve_names.
2650
2651pointQ (EccPoint) -- an ECC  point  representating  the
2652                       public component
2653
2654d (integer) -- A scalar representating the private com‐
2655                       ponent
2656
2657              export_key(**kwargs)
2658                     Export this ECC key.
2659
2660                     Parameters
2661
2662format (string) --
2663
2664                              The format to use for encoding the key:
2665
2666'DER'. The key will be encoded  in  ASN.1  DER
2667                                format  (binary).  For a public key, the ASN.1
2668                                subjectPublicKeyInfo  structure   defined   in
2669                                RFC5480  will be used.  For a private key, the
2670                                ASN.1  ECPrivateKey   structure   defined   in
2671                                RFC5915  is  used  instead  (possibly within a
2672                                PKCS#8 envelope, see the  use_pkcs8  flag  be‐
2673                                low).
2674
2675'PEM'.  The key will be encoded in a PEM enve‐
2676                                lope (ASCII).
2677
2678'OpenSSH'. The key  will  be  encoded  in  the
2679                                OpenSSH format (ASCII, public keys only).
2680
2681
2682passphrase   (byte  string  or  string)  --  The
2683                              passphrase to use  for  protecting  the  private
2684                              key.
2685
2686use_pkcs8 (boolean) --
2687
2688                              Only relevant for private keys.
2689
2690                              If  True  (default  and recommended), the PKCS#8
2691                              representation will be used.
2692
2693                              If False, the much weaker PEM encryption  mecha‐
2694                              nism will be used.
2695
2696
2697protection (string) -- When a private key is ex‐
2698                              ported with password-protection and PKCS#8 (both
2699                              DER  and  PEM  formats),  this parameter MUST be
2700                              present and be a valid  algorithm  supported  by
2701                              Crypto.IO.PKCS8.    It  is  recommended  to  use
2702                              PBKDF2WithHMAC-SHA1AndAES128-CBC.
2703
2704compress (boolean) --
2705
2706                              If True, a more compact  representation  of  the
2707                              public key with the X-coordinate only is used.
2708
2709                              If  False (default), the full public key will be
2710                              exported.
2711
2712
2713                     WARNING:
2714                        If you don't provide a  passphrase,  the  private  key
2715                        will be exported in the clear!
2716
2717                     NOTE:
2718                        When  exporting a private key with password-protection
2719                        and PKCS#8 (both DER and PEM formats), any  extra  pa‐
2720                        rameters   to   export_key()   will   be   passed   to
2721                        Crypto.IO.PKCS8.
2722
2723                     Returns
2724                            A multi-line string (for PEM and OpenSSH) or bytes
2725                            (for DER) with the encoded key.
2726
2727              has_private()
2728                     True if this key can be used for making signatures or de‐
2729                     crypting data.
2730
2731              public_key()
2732                     A matching ECC public key.
2733
2734                     Returns
2735                            a new EccKey object
2736
2737       class Crypto.PublicKey.ECC.EccPoint(x, y, curve='p256')
2738              A class to abstract a point over an Elliptic Curve.
2739
2740              The class support special methods for:
2741
2742              • Adding two points: R = S + T
2743
2744              • In-place addition: S += T
2745
2746              • Negating a point: R = -T
2747
2748              • Comparing two points: if S == T: ...
2749
2750              • Multiplying a point by a scalar: R = S*k
2751
2752              • In-place multiplication by a scalar: T *= k
2753
2754              Variables
2755
2756x (integer) -- The affine X-coordinate of the ECC point
2757
2758y (integer) -- The affine Y-coordinate of the ECC point
2759
2760xy -- The tuple with X- and Y- coordinates
2761
2762              copy() Return a copy of this point.
2763
2764              double()
2765                     Double this point (in-place operation).
2766
2767                     Return EccPoint : this same object (to enable chaining)
2768
2769              is_point_at_infinity()
2770                     True if this is the point-at-infinity.
2771
2772              point_at_infinity()
2773                     Return the point-at-infinity for the curve this point  is
2774                     on.
2775
2776              size_in_bits()
2777                     Size of each coordinate, in bits.
2778
2779              size_in_bytes()
2780                     Size of each coordinate, in bytes.
2781
2782       exception Crypto.PublicKey.ECC.UnsupportedEccFeature
2783
2784       Crypto.PublicKey.ECC.construct(**kwargs)
2785              Build  a new ECC key (private or public) starting from some base
2786              components.
2787
2788              Parameters
2789
2790curve (string) -- Mandatory. It must be  a  curve  name
2791                       defined in curve_names.
2792
2793d  (integer)  --  Only for a private key. It must be in
2794                       the range [1..order-1].
2795
2796point_x (integer) -- Mandatory for a public key. X  co‐
2797                       ordinate (affine) of the ECC point.
2798
2799point_y  (integer) -- Mandatory for a public key. Y co‐
2800                       ordinate (affine) of the ECC point.
2801
2802              Returns
2803                     a new ECC key object
2804
2805              Return type
2806                     EccKey
2807
2808       Crypto.PublicKey.ECC.generate(**kwargs)
2809              Generate a new private key on the given curve.
2810
2811              Parameters
2812
2813curve (string) -- Mandatory. It must be  a  curve  name
2814                       defined in curve_names.
2815
2816randfunc  (callable)  -- Optional. The RNG to read ran‐
2817                       domness   from.    If   None,    Crypto.Random.get_ran‐
2818                       dom_bytes() is used.
2819
2820       Crypto.PublicKey.ECC.import_key(encoded, passphrase=None)
2821              Import an ECC key (public or private).
2822
2823              Parameters
2824
2825encoded (bytes or multi-line string) --
2826
2827                       The ECC key to import.
2828
2829                       An ECC public key can be:
2830
2831                       • An X.509 certificate, binary (DER) or ASCII (PEM)
2832
2833                       • An  X.509 subjectPublicKeyInfo, binary (DER) or ASCII
2834                         (PEM)
2835
2836                       • An OpenSSH line (e.g. the content of ~/.ssh/id_ecdsa,
2837                         ASCII)
2838
2839                       An ECC private key can be:
2840
2841                       • In  binary  format  (DER, see section 3 of RFC5915 or
2842                         PKCS#8)
2843
2844                       • In ASCII format (PEM or OpenSSH 6.5+)
2845
2846                       Private keys can be in the clear or password-protected.
2847
2848                       For details  about  the  PEM  encoding,  see  RFC1421/‐
2849                       RFC1423.
2850
2851
2852passphrase  (byte  string) -- The passphrase to use for
2853                       decrypting a private key.  Encryption  may  be  applied
2854                       protected  at  the  PEM  level  or at the PKCS#8 level.
2855                       This parameter is ignored if the key in  input  is  not
2856                       encrypted.
2857
2858              Returns
2859                     a new ECC key object
2860
2861              Return type
2862                     EccKey
2863
2864              Raises ValueError -- when the given key cannot be parsed (possi‐
2865                     bly because
2866                         the pass phrase is wrong).
2867
2868       • RSA keys
2869
2870       • DSA keys
2871
2872       • Elliptic Curve keys
2873
2874   Obsolete key type
2875   El Gamal
2876       WARNING:
2877          Even though ElGamal algorithms are in theory reasonably  secure,  in
2878          practice  there  are  no real good reasons to prefer them to rsa in‐
2879          stead.
2880
2881   Signature algorithm
2882       The security of the ElGamal signature scheme is based (like DSA) on the
2883       discrete  logarithm problem (DLP). Given a cyclic group, a generator g,
2884       and an element h, it is hard to find an integer x such that g^x = h.
2885
2886       The group is the largest multiplicative sub-group of the integers  mod‐
2887       ulo  p,  with p prime.  The signer holds a value x (0<x<p-1) as private
2888       key, and its public key (y where y=g^x \text{ mod } p) is distributed.
2889
2890       The ElGamal signature is twice as big as p.
2891
2892   Encryption algorithm
2893       The security of the ElGamal encryption scheme is based on the  computa‐
2894       tional  Diffie-Hellman problem (CDH). Given a cyclic group, a generator
2895       g, and two integers a and b, it is difficult to find the element g^{ab}
2896       when only g^a and g^b are known, and not a and b.
2897
2898       As before, the group is the largest multiplicative sub-group of the in‐
2899       tegers modulo p, with p prime.  The receiver holds a value a  (0<a<p-1)
2900       as  private  key,  and  its  public key (b where b=g^a) is given to the
2901       sender.
2902
2903       The ElGamal ciphertext is twice as big as p.
2904
2905   Domain parameters
2906       For both signature and encryption schemes, the values (p,g) are  called
2907       domain  parameters.   They are not sensitive but must be distributed to
2908       all parties (senders and receivers).  Different signers can  share  the
2909       same  domain  parameters, as can different recipients of encrypted mes‐
2910       sages.
2911
2912   Security
2913       Both DLP and CDH problem are believed to be difficult,  and  they  have
2914       been proved such (and therefore secure) for more than 30 years.
2915
2916       The cryptographic strength is linked to the magnitude of p.  In 2017, a
2917       sufficient size for p is deemed to be 2048 bits.  For more information,
2918       see the most recent ECRYPT report.
2919
2920       The signature is four times larger than the equivalent DSA, and the ci‐
2921       phertext is two times larger than the equivalent RSA.
2922
2923   Functionality
2924       This module provides facilities for generating  new  ElGamal  keys  and
2925       constructing them from known components.
2926
2927       class Crypto.PublicKey.ElGamal.ElGamalKey(randfunc=None)
2928              Class  defining  an  ElGamal  key.  Do not instantiate directly.
2929              Use generate() or construct() instead.
2930
2931              Variables
2932
2933p -- Modulus
2934
2935g -- Generator
2936
2937y (integer) -- Public key component
2938
2939x (integer) -- Private key component
2940
2941              has_private()
2942                     Whether this is an ElGamal private key
2943
2944              publickey()
2945                     A matching ElGamal public key.
2946
2947                     Returns
2948                            a new ElGamalKey object
2949
2950       Crypto.PublicKey.ElGamal.construct(tup)
2951              Construct an ElGamal key from a tuple of  valid  ElGamal  compo‐
2952              nents.
2953
2954              The  modulus  p  must be a prime.  The following conditions must
2955              apply:
2956
2957                                       \begin{align}
2958              &1 < g < p-1 \\ &g^{p-1} = 1 \text{ mod } 1 \\ &1 < x <  p-1  \\
2959              &g^x = y \text{ mod } p \end{align}
2960
2961              Parameters
2962                     tup (tuple) --
2963
2964                     A tuple with either 3 or 4 integers, in the following or‐
2965                     der:
2966
2967                     1. Modulus (p).
2968
2969                     2. Generator (g).
2970
2971                     3. Public key (y).
2972
2973                     4. Private key (x). Optional.
2974
2975
2976              Raises ValueError -- when the key being imported fails the  most
2977                     basic ElGamal validity checks.
2978
2979              Returns
2980                     an ElGamalKey object
2981
2982       Crypto.PublicKey.ElGamal.generate(bits, randfunc)
2983              Randomly generate a fresh, new ElGamal key.
2984
2985              The  key  will be safe for use for both encryption and signature
2986              (although it should be used for only one purpose).
2987
2988              Parameters
2989
2990bits (int) -- Key length, or size (in bits) of the mod‐
2991                       ulus p.  The recommended value is 2048.
2992
2993randfunc  (callable)  -- Random number generation func‐
2994                       tion; it should accept a single integer N and return  a
2995                       string of random N random bytes.
2996
2997              Returns
2998                     an ElGamalKey object
2999
3000       • ElGamal keys
3001
3002   Crypto.Protocol package
3003   Key Derivation Functions
3004       This module contains a collection of standard key derivation functions.
3005
3006       A  key  derivation  function  derives one or more secondary secret keys
3007       from one primary secret (a master key or a pass phrase).
3008
3009       This is typically done to insulate the secondary keys from each  other,
3010       to  avoid  that  leakage of a secondary key compromises the security of
3011       the master key, or to thwart attacks on pass phrases (e.g. via  rainbow
3012       tables).
3013
3014   PBKDF2
3015       PBKDF2  is the most widespread algorithm for deriving keys from a pass‐
3016       word, originally defined in version 2.0 of the PKCS#5  standard  or  in
3017       RFC2898.
3018
3019       It  is  computationally expensive (a property that can be tuned via the
3020       count parameter) so as to thwart dictionary and rainbow tables attacks.
3021       However,  it  uses a very limited amount of RAM which makes it insuffi‐
3022       ciently protected against advanced and motivated adversaries  that  can
3023       leverage GPUs.
3024
3025       New applications and protocols should use scrypt or bcrypt instead.
3026
3027       For example, if you need to derive two AES256 keys:
3028
3029          from Crypto.Protocol.KDF import PBKDF2
3030          from Crypto.Hash import SHA512
3031          from Crypto.Random import get_random_bytes
3032
3033          password = b'my super secret'
3034          salt = get_random_bytes(16)
3035          keys = PBKDF2(password, salt, 64, count=1000000, hmac_hash_module=SHA512)
3036          key1 = keys[:32]
3037          key2 = keys[32:]
3038
3039       Crypto.Protocol.KDF.PBKDF2(password,    salt,   dkLen=16,   count=1000,
3040       prf=None, hmac_hash_module=None)
3041              Derive one or more keys from a password (or passphrase).
3042
3043              This function performs key derivation according  to  the  PKCS#5
3044              standard (v2.0).
3045
3046              Parameters
3047
3048password (string or byte string) -- The secret password
3049                       to generate the key from.
3050
3051salt (string or byte string) -- A (byte) string to  use
3052                       for  better  protection  from dictionary attacks.  This
3053                       value does not need to be kept secret, but it should be
3054                       randomly  chosen for each derivation. It is recommended
3055                       to use at least 16 bytes.
3056
3057dkLen (integer) --
3058
3059                       The cumulative length of the keys to produce.
3060
3061                       Due to a flaw in the PBKDF2 design, you should not  re‐
3062                       quest more bytes than the prf can output. For instance,
3063                       dkLen should not exceed 20 bytes  in  combination  with
3064                       HMAC-SHA1.
3065
3066
3067count (integer) --
3068
3069                       The  number  of iterations to carry out. The higher the
3070                       value, the slower and the more secure the function  be‐
3071                       comes.
3072
3073                       You  should  find the maximum number of iterations that
3074                       keeps the key derivation still acceptable on the  slow‐
3075                       est hardware you must support.
3076
3077                       Although  the  default value is 1000, it is recommended
3078                       to use at least 1000000 (1 million) iterations.
3079
3080
3081prf (callable) -- A pseudorandom function. It must be a
3082                       function  that  returns a pseudorandom byte string from
3083                       two parameters: a secret and a salt.   The  slower  the
3084                       algorithm, the more secure the derivation function.  If
3085                       not specified, HMAC-SHA1 is used.
3086
3087hmac_hash_module (module) -- A module from  Crypto.Hash
3088                       implementing a Merkle-Damgard cryptographic hash, which
3089                       PBKDF2 must use in combination with HMAC.  This parame‐
3090                       ter is mutually exclusive with prf.
3091
3092              Returns
3093                     A byte string of length dkLen that can be used as key ma‐
3094                     terial.  If you want multiple keys, just  break  up  this
3095                     string into segments of the desired length.
3096
3097   scrypt
3098       scrypt  is  a  password-based  key derivation function created by Colin
3099       Percival, described in his paper "Stronger key derivation  via  sequen‐
3100       tial memory-hard functions" and in RFC7914.
3101
3102       In  addition  to being computationally expensive, it is also memory in‐
3103       tensive and therefore more secure against the risk of custom ASICs.
3104
3105       Example:
3106
3107          from Crypto.Protocol.KDF import scrypt
3108          from Crypto.Random import get_random_bytes
3109
3110          password = b'my super secret'
3111          salt = get_random_bytes(16)
3112          key = scrypt(password, salt, 16, N=2**14, r=8, p=1)
3113
3114       Crypto.Protocol.KDF.scrypt(password,   salt,   key_len,   N,   r,    p,
3115       num_keys=1)
3116              Derive one or more keys from a passphrase.
3117
3118              Parameters
3119
3120password (string) -- The secret pass phrase to generate
3121                       the keys from.
3122
3123salt (string) -- A string to use for better  protection
3124                       from  dictionary  attacks.  This value does not need to
3125                       be kept secret, but it should be  randomly  chosen  for
3126                       each  derivation.   It is recommended to be at least 16
3127                       bytes long.
3128
3129key_len (integer) -- The length in bytes of  every  de‐
3130                       rived key.
3131
3132N  (integer) -- CPU/Memory cost parameter. It must be a
3133                       power of 2 and less than 2^{32}.
3134
3135r (integer) -- Block size parameter.
3136
3137p (integer) -- Parallelization parameter.  It  must  be
3138                       no greater than (2^{32}-1)/(4r).
3139
3140num_keys (integer) -- The number of keys to derive. Ev‐
3141                       ery key is key_len bytes long.  By default, only 1  key
3142                       is  generated.   The  maximum  cumulative length of all
3143                       keys is (2^{32}-1)*32 (that is, 128TB).
3144
3145              A good choice of parameters (N, r , p) was  suggested  by  Colin
3146              Percival in his presentation in 2009:
3147
3148( 2¹⁴, 8, 1 ) for interactive logins (≤100ms)
3149
3150( 2²⁰, 8, 1 ) for file encryption (≤5s)
3151
3152              Returns
3153                     A byte string or a tuple of byte strings.
3154
3155   bcrypt
3156       bcrypt  is  a  password  hashing  function designed by Niels Provos and
3157       David Mazières.
3158
3159       In addition to being computationally expensive, it is also  memory  in‐
3160       tensive and therefore more secure against the risk of custom ASICs.
3161
3162       This implementation only supports bcrypt hashes with prefix $2a.
3163
3164       By  design,  bcrypt  only accepts passwords up to 72 byte long.  If you
3165       want to hash passwords with no restrictions on their length, it is com‐
3166       mon  practice  to apply a cryptographic hash and then BASE64-encode For
3167       instance:
3168
3169          from base64 import b64encode
3170          from Crypto.Hash import SHA256
3171          from Crypto.Protocol.KDF import bcrypt
3172
3173          password = b"test"
3174          b64pwd = b64encode(SHA256.new(password).digest())
3175          bcrypt_hash = bcrypt(b64pwd, 12)
3176
3177       and to check them:
3178
3179          from base64 import b64encode
3180          from Crypto.Hash import SHA256
3181          from Crypto.Protocol.KDF import bcrypt
3182
3183          password_to_test = b"test"
3184          try:
3185              b64pwd = b64encode(SHA256.new(password).digest())
3186              bcrypt_check(b64pwd, bcrypt_hash)
3187          except ValueError:
3188              print("Incorrect password")
3189
3190       Crypto.Protocol.KDF.bcrypt(password, cost, salt=None)
3191              Hash a password into a key, using the OpenBSD bcrypt protocol.
3192
3193              Parameters
3194
3195password (byte string or string) -- The secret password
3196                       or  pass phrase.  It must be at most 72 bytes long.  It
3197                       must not contain the zero byte.  Unicode  strings  will
3198                       be encoded as UTF-8.
3199
3200cost  (integer) -- The exponential factor that makes it
3201                       slower to compute the hash.  It must be in the range  4
3202                       to 31.  A value of at least 12 is recommended.
3203
3204salt  (byte  string) -- Optional. Random byte string to
3205                       thwarts dictionary and rainbow table attacks.  It  must
3206                       be  16  bytes  long.   If not passed, a random value is
3207                       generated.
3208
3209              Return (byte string):
3210                     The bcrypt hash
3211
3212              Raises ValueError -- if password is longer than 72 bytes  or  if
3213                     it contains the zero byte
3214
3215       Crypto.Protocol.KDF.bcrypt_check(password, bcrypt_hash)
3216              Verify if the provided password matches the given bcrypt hash.
3217
3218              Parameters
3219
3220password (byte string or string) -- The secret password
3221                       or pass phrase to test.  It must be at  most  72  bytes
3222                       long.   It  must  not  contain  the zero byte.  Unicode
3223                       strings will be encoded as UTF-8.
3224
3225bcrypt_hash (byte string, bytearray) --  The  reference
3226                       bcrypt hash the password needs to be checked against.
3227
3228              Raises ValueError -- if the password does not match
3229
3230   HKDF
3231       The  HMAC-based  Extract-and-Expand  key derivation function (HKDF) was
3232       designed by Hugo Krawczyk.  It is standardized in RFC 5869 and in  NIST
3233       SP-800 56C.
3234
3235       This  KDF  is not suitable for deriving keys from a password or for key
3236       stretching.
3237
3238       Example, for deriving two AES256 keys:
3239
3240          from Crypto.Protocol.KDF import HKDF
3241          from Crypto.Hash import SHA512
3242          from Crypto.Random import get_random_bytes
3243
3244          salt = get_random_bytes(16)
3245          key1, key2 = HKDF(master_secret, 32, salt, SHA512, 2)
3246
3247       Crypto.Protocol.KDF.HKDF(master, key_len,  salt,  hashmod,  num_keys=1,
3248       context=None)
3249              Derive  one  or  more  keys  from  a  master  secret  using  the
3250              HMAC-based KDF defined in RFC5869.
3251
3252              Parameters
3253
3254master (byte string) -- The unguessable value  used  by
3255                       the  KDF  to  generate  the  other  keys.  It must be a
3256                       high-entropy secret, though  not  necessarily  uniform.
3257                       It must not be a password.
3258
3259salt (byte string) -- A non-secret, reusable value that
3260                       strengthens the randomness extraction  step.   Ideally,
3261                       it  is  as  long as the digest size of the chosen hash.
3262                       If empty, a string of zeroes in used.
3263
3264key_len (integer) -- The length in bytes of  every  de‐
3265                       rived key.
3266
3267hashmod (module) -- A cryptographic hash algorithm from
3268                       Crypto.Hash.  Crypto.Hash.SHA512 is a good choice.
3269
3270num_keys (integer) -- The number of keys to derive. Ev‐
3271                       ery  key is key_len bytes long.  The maximum cumulative
3272                       length of all keys is 255 times the digest size.
3273
3274context (byte string) -- Optional identifier describing
3275                       what the keys are used for.
3276
3277              Returns
3278                     A byte string or a tuple of byte strings.
3279
3280   PBKDF1
3281       PBKDF1  is an old key derivation function defined in version 2.0 of the
3282       PKCS#5 standard (v1.5) or in RFC2898.
3283
3284       WARNING:
3285          Newer applications should use the more secure and  versatile  scrypt
3286          instead.
3287
3288       Crypto.Protocol.KDF.PBKDF1(password,     salt,    dkLen,    count=1000,
3289       hashAlgo=None)
3290              Derive one key from a password (or passphrase).
3291
3292              This function performs key derivation according to an  old  ver‐
3293              sion of the PKCS#5 standard (v1.5) or RFC2898.
3294
3295              Parameters
3296
3297password  (string)  --  The secret password to generate
3298                       the key from.
3299
3300salt (byte string) -- An 8 byte string to use for  bet‐
3301                       ter  protection  from  dictionary  attacks.  This value
3302                       does not need to be kept secret, but it should be  ran‐
3303                       domly chosen for each derivation.
3304
3305dkLen  (integer)  -- The length of the desired key. The
3306                       default  is  16  bytes,  suitable  for   instance   for
3307                       Crypto.Cipher.AES.
3308
3309count  (integer)  --  The number of iterations to carry
3310                       out. The recommendation is 1000 or more.
3311
3312hashAlgo (module) -- The hash algorithm to  use,  as  a
3313                       module  or an object from the Crypto.Hash package.  The
3314                       digest length must be no shorter than dkLen.   The  de‐
3315                       fault algorithm is Crypto.Hash.SHA1.
3316
3317              Returns
3318                     A byte string of length dkLen that can be used as key.
3319
3320   Secret Sharing Schemes
3321       This  module  implements the Shamir's secret sharing protocol described
3322       in the paper "How to share a secret".
3323
3324       The secret can be split into an arbitrary number of  shares  (n),  such
3325       that  it is sufficient to collect just k of them to reconstruct it (k <
3326       n).  For instance, one may want to grant 16 people the ability  to  ac‐
3327       cess  a  system  with  a pass code, at the condition that at least 3 of
3328       them are present at the same time. As they join their shares, the  pass
3329       code is revealed.  In that case, n=16 and k=3.
3330
3331       In  the  Shamir's  secret  sharing  scheme, the n shares are created by
3332       first defining a polynomial of degree k-1:
3333
3334       q(x) = a_0 + a_1 x + a_2 x^2 + \ldots + a_{k-1} x^{k-1}
3335
3336       The coefficient a_0 is fixed with the secret value.   The  coefficients
3337       a_1  \ldots  a_{k-1}  are  random and they are discarded as soon as the
3338       shares are created.
3339
3340       Each share is a pair (x_i, y_i), where x_i is an arbitrary  but  unique
3341       number assigned to the share's recipient and y_i=q(x_i).
3342
3343       This implementation has the following properties:
3344
3345       • The secret is a byte string of 16 bytes (e.g. an AES 128 key).
3346
3347       • Each share is a byte string of 16 bytes.
3348
3349       • The  recipients of the shares are assigned an integer starting from 1
3350         (share number x_i).
3351
3352       • The polynomial q(x) is defined over the field  GF(2^{128})  with  the
3353         same  irriducible  polynomial as used in AES-GCM: 1 + x + x^2 + x^7 +
3354         x^{128}.
3355
3356       • It can be compatible with the popular ssss tool when  used  with  the
3357         128  bit security level and no dispersion: the command line arguments
3358         must include -s 128 -D.  Note that ssss  uses  a  slightly  different
3359         polynomial:
3360
3361         r(x) = a_0 + a_1 x + a_2 x^2 + \ldots + a_{k-1} x^{k-1} + x^k
3362
3363         which requires you to specify ssss=True when calling split() and com‐
3364         bine().
3365
3366       Each recipient needs to hold both the share number (x_i, which  is  not
3367       confidential) and the secret (which needs to be protected securely).
3368
3369       As an example, the following code shows how to protect a file meant for
3370       5 people, in such a way that any 2 of them are sufficient to reassemble
3371       it:
3372
3373          >>> from binascii import hexlify
3374          >>> from Crypto.Cipher import AES
3375          >>> from Crypto.Random import get_random_bytes
3376          >>> from Crypto.Protocol.SecretSharing import Shamir
3377          >>>
3378          >>> key = get_random_bytes(16)
3379          >>> shares = Shamir.split(2, 5, key)
3380          >>> for idx, share in shares:
3381          >>>     print "Index #%d: %s" % (idx, hexlify(share))
3382          >>>
3383          >>> with open("clear.txt", "rb") as fi, open("enc.txt", "wb") as fo:
3384          >>>     cipher = AES.new(key, AES.MODE_EAX)
3385          >>>     ct, tag = cipher.encrypt(fi.read()), cipher.digest()
3386          >>>     fo.write(nonce + tag + ct)
3387
3388       Each person can be given one share and the encrypted file.
3389
3390       When  2  people gather together with their shares, they can decrypt the
3391       file:
3392
3393          >>> from binascii import unhexlify
3394          >>> from Crypto.Cipher import AES
3395          >>> from Crypto.Protocol.SecretSharing import Shamir
3396          >>>
3397          >>> shares = []
3398          >>> for x in range(2):
3399          >>>     in_str = raw_input("Enter index and share separated by comma: ")
3400          >>>     idx, share = [ strip(s) for s in in_str.split(",") ]
3401          >>>     shares.append((idx, unhexlify(share)))
3402          >>> key = Shamir.combine(shares)
3403          >>>
3404          >>> with open("enc.txt", "rb") as fi:
3405          >>>     nonce, tag = [ fi.read(16) for x in range(2) ]
3406          >>>     cipher = AES.new(key, AES.MODE_EAX, nonce)
3407          >>>     try:
3408          >>>         result = cipher.decrypt(fi.read())
3409          >>>         cipher.verify(tag)
3410          >>>         with open("clear2.txt", "wb") as fo:
3411          >>>             fo.write(result)
3412          >>>     except ValueError:
3413          >>>         print "The shares were incorrect"
3414
3415       ATTENTION:
3416          Reconstruction may succeed but still produce the incorrect secret if
3417          any  of the presented shares is incorrect (due to data corruption or
3418          to a malicious participant).
3419
3420          It is extremely important to also use  an  authentication  mechanism
3421          (such as the EAX cipher mode in the example).
3422
3423       class Crypto.Protocol.SecretSharing.Shamir
3424              Shamir's secret sharing scheme.
3425
3426              A secret is split into n shares, and it is sufficient to collect
3427              k of them to reconstruct the secret.
3428
3429              static combine(shares, ssss=False)
3430                     Recombine a secret, if enough shares are presented.
3431
3432                     Parameters
3433
3434shares (tuples) -- The k tuples, each  containin
3435                              the  index  (an  integer)  and the share (a byte
3436                              string, 16 bytes long) that were assigned  to  a
3437                              participant.
3438
3439ssss (bool) -- If True, the shares were produced
3440                              by the ssss utility.  Default: False.
3441
3442                     Returns
3443                            The original secret, as a byte  string  (16  bytes
3444                            long).
3445
3446              static split(k, n, secret, ssss=False)
3447                     Split a secret into n shares.
3448
3449                     The secret can be reconstructed later using just k shares
3450                     out of the original n.  Each share must be kept confiden‐
3451                     tial to the person it was assigned to.
3452
3453                     Each share is associated to an index (starting from 1).
3454
3455                     Parameters
3456
3457k  (integer)  -- The sufficient number of shares
3458                              to reconstruct the secret (k < n).
3459
3460n (integer) -- The number of  shares  that  this
3461                              method will create.
3462
3463secret  (byte  string)  --  A  byte string of 16
3464                              bytes (e.g. the AES 128 key).
3465
3466ssss (bool) -- If True, the shares can  be  used
3467                              with the ssss utility.  Default: False.
3468
3469                     Return (tuples):
3470                            n  tuples.  A  tuple is meant for each participant
3471                            and it contains two items:
3472
3473                            1. the unique index (an integer)
3474
3475                            2. the share (a byte string, 16 bytes)
3476
3477       • kdf
3478
3479       • ss
3480
3481   Crypto.IO package
3482       Modules for reading and writing cryptographic data.
3483
3484       • pem
3485
3486       • pkcs8
3487
3488   PEM
3489       Set of functions for encapsulating data according to the PEM format.
3490
3491       PEM (Privacy Enhanced Mail) was an IETF standard  for  securing  emails
3492       via a Public Key Infrastructure. It is specified in RFC 1421-1424.
3493
3494       Even  though it has been abandoned, the simple message encapsulation it
3495       defined is still widely used today for  encoding  binary  cryptographic
3496       objects like keys and certificates into text.
3497
3498       Crypto.IO.PEM.decode(pem_data, passphrase=None)
3499              Decode a PEM block into binary.
3500
3501              Parameters
3502
3503pem_data (string) -- The PEM block.
3504
3505passphrase  (byte string) -- If given and the PEM block
3506                       is  encrypted,  the  key  will  be  derived  from   the
3507                       passphrase.
3508
3509              Returns
3510                     A  tuple  with  the binary data, the marker string, and a
3511                     boolean to indicate if decryption was performed.
3512
3513              Raises ValueError -- if decoding fails, if the PEM file  is  en‐
3514                     crypted and no passphrase has
3515                         been provided or if the passphrase is incorrect.
3516
3517       Crypto.IO.PEM.encode(data, marker, passphrase=None, randfunc=None)
3518              Encode a piece of binary data into PEM format.
3519
3520              Parameters
3521
3522data  (byte  string) -- The piece of binary data to en‐
3523                       code.
3524
3525marker (string) -- The marker for the PEM  block  (e.g.
3526                       "PUBLIC  KEY").   Note that there is no official master
3527                       list for all allowed markers.  Still, you can refer  to
3528                       the OpenSSL source code.
3529
3530passphrase  (byte  string)  --  If given, the PEM block
3531                       will  be  encrypted.  The  key  is  derived  from   the
3532                       passphrase.
3533
3534randfunc  (callable)  -- Random number generation func‐
3535                       tion; it accepts an integer N and returns a byte string
3536                       of  random  data, N bytes long. If not given, a new one
3537                       is instantiated.
3538
3539              Returns
3540                     The PEM block, as a string.
3541
3542   PKCS#8
3543       PKCS#8 is a standard for storing and transferring private key  informa‐
3544       tion.  The wrapped key can either be clear or encrypted.
3545
3546       All encryption algorithms are based on passphrase-based key derivation.
3547       The following mechanisms are fully supported:
3548
3549PBKDF2WithHMAC-SHA1AndAES128-CBC
3550
3551PBKDF2WithHMAC-SHA1AndAES192-CBC
3552
3553PBKDF2WithHMAC-SHA1AndAES256-CBC
3554
3555PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC
3556
3557scryptAndAES128-CBC
3558
3559scryptAndAES192-CBC
3560
3561scryptAndAES256-CBC
3562
3563       The following mechanisms are only supported for importing  keys.   They
3564       are  much  weaker than the ones listed above, and they are provided for
3565       backward compatibility only:
3566
3567pbeWithMD5AndRC2-CBC
3568
3569pbeWithMD5AndDES-CBC
3570
3571pbeWithSHA1AndRC2-CBC
3572
3573pbeWithSHA1AndDES-CBC
3574
3575       Crypto.IO.PKCS8.unwrap(p8_private_key, passphrase=None)
3576              Unwrap a private key from a PKCS#8 blob (clear or encrypted).
3577
3578              Parameters
3579
3580p8_private_key (byte string) -- The private key wrapped
3581                       into a PKCS#8 blob, DER encoded.
3582
3583passphrase (byte string or string) -- The passphrase to
3584                       use to decrypt the blob (if it is encrypted).
3585
3586              Returns
3587                     A tuple containing
3588
3589                        1. the algorithm identifier of the wrapped  key  (OID,
3590                           dotted string)
3591
3592                        2. the private key (byte string, DER encoded)
3593
3594                        3. the  associated  parameters  (byte  string, DER en‐
3595                           coded) or None
3596
3597
3598              Raises ValueError -- if decoding fails
3599
3600       Crypto.IO.PKCS8.wrap(private_key,  key_oid,  passphrase=None,   protec‐
3601       tion=None, prot_params=None, key_params=None, randfunc=None)
3602              Wrap a private key into a PKCS#8 blob (clear or encrypted).
3603
3604              Parameters
3605
3606private_key (byte string) -- The private key encoded in
3607                       binary form. The actual encoding is algorithm specific.
3608                       In most cases, it is DER.
3609
3610key_oid  (string) -- The object identifier (OID) of the
3611                       private key to wrap.   It  is  a  dotted  string,  like
3612                       1.2.840.113549.1.1.1 (for RSA keys).
3613
3614passphrase  (bytes  string  or  string)  --  The secret
3615                       passphrase from which the wrapping key is derived.  Set
3616                       it only if encryption is required.
3617
3618protection  (string) -- The identifier of the algorithm
3619                       to use for securely  wrapping  the  key.   The  default
3620                       value is PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC.
3621
3622prot_params (dictionary) --
3623
3624                       Parameters for the protection algorithm.
3625
3626                           ┌────────────────┬────────────────────────────┐
3627                           │Key             │ Description                │
3628                           ├────────────────┼────────────────────────────┤
3629                           │iteration_count │ The  KDF  algorithm is re‐ │
3630                           │                │ peated  several  times  to │
3631                           │                │ slow  down brute force at‐ │
3632                           │                │ tacks on passwords (called │
3633                           │                │ N  or  CPU/memory  cost in │
3634                           │                │ scrypt).    The    default │
3635                           │                │ value  for PBKDF2 is 1000. │
3636                           │                │ The  default   value   for │
3637                           │                │ scrypt is 16384.           │
3638                           └────────────────┴────────────────────────────┘
3639
3640
3641
3642
3643
3644                           │salt_size       │ Salt  is  used  to  thwart │
3645                           │                │ dictionary and rainbow at‐ │
3646                           │                │ tacks  on  passwords.  The │
3647                           │                │ default value is 8 bytes.  │
3648                           ├────────────────┼────────────────────────────┤
3649                           │block_size      │ (scrypt only)  Memory-cost │
3650                           │                │ (r).  The default value is │
3651                           │                │ 8.                         │
3652                           ├────────────────┼────────────────────────────┤
3653                           │parallelization │ (scrypt   only)   CPU-cost │
3654                           │                │ (p).  The default value is │
3655                           │                │ 1.                         │
3656                           └────────────────┴────────────────────────────┘
3657
3658
3659key_params (DER object) -- The algorithm parameters as‐
3660                       sociated  to the private key.  It is required for algo‐
3661                       rithms like DSA, but not for others like RSA.
3662
3663randfunc (callable) -- Random number  generation  func‐
3664                       tion;  it should accept a single integer N and return a
3665                       string of random data, N bytes long.  If not specified,
3666                       a new RNG will be instantiated from Crypto.Random.
3667
3668              Returns
3669                     The PKCS#8-wrapped private key (possibly encrypted), as a
3670                     byte string.
3671
3672   Crypto.Random package
3673       Crypto.Random.get_random_bytes(N)
3674              Return a random byte string of length N.
3675
3676   Crypto.Random.random module
3677       Crypto.Random.random.getrandbits(N)
3678              Return a random integer, at most N bits long.
3679
3680       Crypto.Random.random.randrange([start], stop[, step])
3681              Return a random integer in the range (start,  stop,  step).   By
3682              default, start is 0 and step is 1.
3683
3684       Crypto.Random.random.randint(a, b)
3685              Return  a  random  integer in the range no smaller than a and no
3686              larger than b.
3687
3688       Crypto.Random.random.choice(seq)
3689              Return a random element picked from the sequence seq.
3690
3691       Crypto.Random.random.shuffle(seq)
3692              Randomly shuffle the sequence seq in-place.
3693
3694       Crypto.Random.random.sample(population, k)
3695              Randomly chooses k distinct elements from the list population.
3696
3697   Crypto.Util package
3698       Useful modules that don't belong in any other package.
3699
3700   Crypto.Util.asn1 module
3701       This module provides minimal support for encoding  and  decoding  ASN.1
3702       DER objects.
3703
3704       class   Crypto.Util.asn1.DerBitString(value=b'',   implicit=None,   ex‐
3705       plicit=None)
3706              Class to model a DER BIT STRING.
3707
3708              An example of encoding is:
3709
3710              >>> from Crypto.Util.asn1 import DerBitString
3711              >>> from binascii import hexlify, unhexlify
3712              >>> bs_der = DerBitString(b'\xaa')
3713              >>> bs_der.value += b'\xbb'
3714              >>> print hexlify(bs_der.encode())
3715
3716              which will show 040300aabb, the DER encoding for the bit  string
3717              b'\xAA\xBB'.
3718
3719              For decoding:
3720
3721              >>> s = unhexlify(b'040300aabb')
3722              >>> try:
3723              >>>   bs_der = DerBitString()
3724              >>>   bs_der.decode(s)
3725              >>>   print hexlify(bs_der.value)
3726              >>> except ValueError:
3727              >>>   print "Not a valid DER BIT STRING"
3728
3729              the output will be aabb.
3730
3731              Variables
3732                     value (byte string) -- The content of the string
3733
3734              decode(der_encoded, strict=False)
3735                     Decode a complete DER BIT STRING, and re-initializes this
3736                     object with it.
3737
3738                     Parameters
3739
3740der_encoded (byte string) -- a complete DER  BIT
3741                              STRING.
3742
3743strict  (boolean) -- Whether decoding must check
3744                              for strict DER compliancy.
3745
3746                     Raises ValueError -- in case of parsing errors.
3747
3748              encode()
3749                     Return the DER BIT STRING,  fully  encoded  as  a  binary
3750                     string.
3751
3752       class     Crypto.Util.asn1.DerInteger(value=0,    implicit=None,    ex‐
3753       plicit=None)
3754              Class to model a DER INTEGER.
3755
3756              An example of encoding is:
3757
3758                 >>> from Crypto.Util.asn1 import DerInteger
3759                 >>> from binascii import hexlify, unhexlify
3760                 >>> int_der = DerInteger(9)
3761                 >>> print hexlify(int_der.encode())
3762
3763              which will show 020109, the DER encoding of 9.
3764
3765              And for decoding:
3766
3767                 >>> s = unhexlify(b'020109')
3768                 >>> try:
3769                 >>>   int_der = DerInteger()
3770                 >>>   int_der.decode(s)
3771                 >>>   print int_der.value
3772                 >>> except ValueError:
3773                 >>>   print "Not a valid DER INTEGER"
3774
3775              the output will be 9.
3776
3777              Variables
3778                     value (integer) -- The integer value
3779
3780              decode(der_encoded, strict=False)
3781                     Decode a complete DER  INTEGER  DER,  and  re-initializes
3782                     this object with it.
3783
3784                     Parameters
3785                            der_encoded  (byte  string)  -- A complete INTEGER
3786                            DER element.
3787
3788                     Raises ValueError -- in case of parsing errors.
3789
3790              encode()
3791                     Return the DER INTEGER, fully encoded as a binary string.
3792
3793       class Crypto.Util.asn1.DerNull
3794              Class to model a DER NULL element.
3795
3796       class    Crypto.Util.asn1.DerObject(asn1Id=None,    payload=b'',    im‐
3797       plicit=None, constructed=False, explicit=None)
3798              Base class for defining a single DER object.
3799
3800              This class should never be directly instantiated.
3801
3802              decode(der_encoded, strict=False)
3803                     Decode  a  complete  DER element, and re-initializes this
3804                     object with it.
3805
3806                     Parameters
3807                            der_encoded (byte string) -- A complete  DER  ele‐
3808                            ment.
3809
3810                     Raises ValueError -- in case of parsing errors.
3811
3812              encode()
3813                     Return  this  DER element, fully encoded as a binary byte
3814                     string.
3815
3816       class   Crypto.Util.asn1.DerObjectId(value='',    implicit=None,    ex‐
3817       plicit=None)
3818              Class to model a DER OBJECT ID.
3819
3820              An example of encoding is:
3821
3822              >>> from Crypto.Util.asn1 import DerObjectId
3823              >>> from binascii import hexlify, unhexlify
3824              >>> oid_der = DerObjectId("1.2")
3825              >>> oid_der.value += ".840.113549.1.1.1"
3826              >>> print hexlify(oid_der.encode())
3827
3828              which will show 06092a864886f70d010101, the DER encoding for the
3829              RSA Object Identifier 1.2.840.113549.1.1.1.
3830
3831              For decoding:
3832
3833              >>> s = unhexlify(b'06092a864886f70d010101')
3834              >>> try:
3835              >>>   oid_der = DerObjectId()
3836              >>>   oid_der.decode(s)
3837              >>>   print oid_der.value
3838              >>> except ValueError:
3839              >>>   print "Not a valid DER OBJECT ID"
3840
3841              the output will be 1.2.840.113549.1.1.1.
3842
3843              Variables
3844                     value (string) -- The Object ID (OID),  a  dot  separated
3845                     list of integers
3846
3847              decode(der_encoded, strict=False)
3848                     Decode  a complete DER OBJECT ID, and re-initializes this
3849                     object with it.
3850
3851                     Parameters
3852
3853der_encoded (byte string) -- A complete DER  OB‐
3854                              JECT ID.
3855
3856strict  (boolean) -- Whether decoding must check
3857                              for strict DER compliancy.
3858
3859                     Raises ValueError -- in case of parsing errors.
3860
3861              encode()
3862                     Return the DER OBJECT  ID,  fully  encoded  as  a  binary
3863                     string.
3864
3865       class Crypto.Util.asn1.DerOctetString(value=b'', implicit=None)
3866              Class to model a DER OCTET STRING.
3867
3868              An example of encoding is:
3869
3870              >>> from Crypto.Util.asn1 import DerOctetString
3871              >>> from binascii import hexlify, unhexlify
3872              >>> os_der = DerOctetString(b'\xaa')
3873              >>> os_der.payload += b'\xbb'
3874              >>> print hexlify(os_der.encode())
3875
3876              which  will  show 0402aabb, the DER encoding for the byte string
3877              b'\xAA\xBB'.
3878
3879              For decoding:
3880
3881              >>> s = unhexlify(b'0402aabb')
3882              >>> try:
3883              >>>   os_der = DerOctetString()
3884              >>>   os_der.decode(s)
3885              >>>   print hexlify(os_der.payload)
3886              >>> except ValueError:
3887              >>>   print "Not a valid DER OCTET STRING"
3888
3889              the output will be aabb.
3890
3891              Variables
3892                     payload (byte string) -- The content of the string
3893
3894       class Crypto.Util.asn1.DerSequence(startSeq=None, implicit=None)
3895              Class to model a DER SEQUENCE.
3896
3897              This object behaves like a dynamic Python sequence.
3898
3899              Sub-elements that are INTEGERs behave like Python integers.
3900
3901              Any other sub-element is a binary string encoded as  a  complete
3902              DER sub-element (TLV).
3903
3904              An example of encoding is:
3905
3906              >>> from Crypto.Util.asn1 import DerSequence, DerInteger
3907              >>> from binascii import hexlify, unhexlify
3908              >>> obj_der = unhexlify('070102')
3909              >>> seq_der = DerSequence([4])
3910              >>> seq_der.append(9)
3911              >>> seq_der.append(obj_der.encode())
3912              >>> print hexlify(seq_der.encode())
3913
3914              which  will show 3009020104020109070102, the DER encoding of the
3915              sequence containing 4, 9, and the object with payload 02.
3916
3917              For decoding:
3918
3919              >>> s = unhexlify(b'3009020104020109070102')
3920              >>> try:
3921              >>>   seq_der = DerSequence()
3922              >>>   seq_der.decode(s)
3923              >>>   print len(seq_der)
3924              >>>   print seq_der[0]
3925              >>>   print seq_der[:]
3926              >>> except ValueError:
3927              >>>   print "Not a valid DER SEQUENCE"
3928
3929              the output will be:
3930
3931                 3
3932                 4
3933                 [4, 9, b'.....']
3934
3935              decode(der_encoded,       strict=False,        nr_elements=None,
3936              only_ints_expected=False)
3937                     Decode  a  complete DER SEQUENCE, and re-initializes this
3938                     object with it.
3939
3940                     Parameters
3941
3942der_encoded (byte string) -- A complete SEQUENCE
3943                              DER element.
3944
3945nr_elements  (None  or  integer or list of inte‐
3946                              gers) -- The number of members the SEQUENCE  can
3947                              have
3948
3949only_ints_expected  (boolean) -- Whether the SE‐
3950                              QUENCE is expected to contain only integers.
3951
3952strict (boolean) -- Whether decoding must  check
3953                              for strict DER compliancy.
3954
3955                     Raises ValueError -- in case of parsing errors.
3956
3957                     DER  INTEGERs are decoded into Python integers. Any other
3958                     DER element is not decoded. Its validity is not checked.
3959
3960              encode()
3961                     Return this DER  SEQUENCE,  fully  encoded  as  a  binary
3962                     string.
3963
3964                     Raises ValueError -- if some elements in the sequence are
3965                            neither integers
3966                                nor byte strings.
3967
3968              hasInts(only_non_negative=True)
3969                     Return the number of items in this sequence that are  in‐
3970                     tegers.
3971
3972                     Parameters
3973                            only_non_negative  (boolean)  -- If True, negative
3974                            integers are not counted in.
3975
3976              hasOnlyInts(only_non_negative=True)
3977                     Return True if all items in this sequence are integers or
3978                     non-negative integers.
3979
3980                     This  function returns False is the sequence is empty, or
3981                     at least one member is not an integer.
3982
3983                     Parameters
3984                            only_non_negative (boolean) -- If True, the  pres‐
3985                            ence of negative integers causes the method to re‐
3986                            turn False.
3987
3988       class Crypto.Util.asn1.DerSetOf(startSet=None, implicit=None)
3989              Class to model a DER SET OF.
3990
3991              An example of encoding is:
3992
3993              >>> from Crypto.Util.asn1 import DerBitString
3994              >>> from binascii import hexlify, unhexlify
3995              >>> so_der = DerSetOf([4,5])
3996              >>> so_der.add(6)
3997              >>> print hexlify(so_der.encode())
3998
3999              which will show 3109020104020105020106, the DER  encoding  of  a
4000              SET OF with items 4,5, and 6.
4001
4002              For decoding:
4003
4004              >>> s = unhexlify(b'3109020104020105020106')
4005              >>> try:
4006              >>>   so_der = DerSetOf()
4007              >>>   so_der.decode(s)
4008              >>>   print [x for x in so_der]
4009              >>> except ValueError:
4010              >>>   print "Not a valid DER SET OF"
4011
4012              the output will be [4, 5, 6].
4013
4014              add(elem)
4015                     Add an element to the set.
4016
4017                     Parameters
4018                            elem (byte string or integer) -- An element of the
4019                            same type of objects already in the set.   It  can
4020                            be an integer or a DER encoded object.
4021
4022              decode(der_encoded, strict=False)
4023                     Decode  a complete SET OF DER element, and re-initializes
4024                     this object with it.
4025
4026                     DER INTEGERs are decoded into Python integers. Any  other
4027                     DER  element  is  left  undecoded;  its  validity  is not
4028                     checked.
4029
4030                     Parameters
4031
4032der_encoded (byte string) -- a complete DER  BIT
4033                              SET OF.
4034
4035strict  (boolean) -- Whether decoding must check
4036                              for strict DER compliancy.
4037
4038                     Raises ValueError -- in case of parsing errors.
4039
4040              encode()
4041                     Return this SET OF DER element, fully encoded as a binary
4042                     string.
4043
4044   Crypto.Util.Padding module
4045       This  module  provides minimal support for adding and removing standard
4046       padding from data. Example:
4047
4048          >>> from Crypto.Util.Padding import pad, unpad
4049          >>> from Crypto.Cipher import AES
4050          >>> from Crypto.Random import get_random_bytes
4051          >>>
4052          >>> data = b'Unaligned'   # 9 bytes
4053          >>> key = get_random_bytes(32)
4054          >>> iv = get_random_bytes(16)
4055          >>>
4056          >>> cipher1 = AES.new(key, AES.MODE_CBC, iv)
4057          >>> ct = cipher1.encrypt(pad(data, 16))
4058          >>>
4059          >>> cipher2 = AES.new(key, AES.MODE_CBC, iv)
4060          >>> pt = unpad(cipher2.decrypt(ct), 16)
4061          >>> assert(data == pt)
4062
4063       Crypto.Util.Padding.pad(data_to_pad, block_size, style='pkcs7')
4064              Apply standard padding.
4065
4066              Parameters
4067
4068data_to_pad (byte string) -- The data that needs to  be
4069                       padded.
4070
4071block_size  (integer)  -- The block boundary to use for
4072                       padding. The output length is guaranteed to be a multi‐
4073                       ple of block_size.
4074
4075style  (string) -- Padding algorithm. It can be 'pkcs7'
4076                       (default), 'iso7816' or 'x923'.
4077
4078              Returns
4079                     the original data with the appropriate padding  added  at
4080                     the end.
4081
4082              Return type
4083                     byte string
4084
4085       Crypto.Util.Padding.unpad(padded_data, block_size, style='pkcs7')
4086              Remove standard padding.
4087
4088              Parameters
4089
4090padded_data  (byte string) -- A piece of data with pad‐
4091                       ding that needs to be stripped.
4092
4093block_size (integer) -- The block boundary to  use  for
4094                       padding.  The  input  length  must  be  a  multiple  of
4095                       block_size.
4096
4097style (string) -- Padding algorithm. It can be  'pkcs7'
4098                       (default), 'iso7816' or 'x923'.
4099
4100              Returns
4101                     data without padding.
4102
4103              Return type
4104                     byte string
4105
4106              Raises ValueError -- if the padding is incorrect.
4107
4108   Crypto.Util.RFC1751 module
4109       Crypto.Util.RFC1751.english_to_key(s)
4110              Transform a string into a corresponding key.
4111
4112              Example:
4113
4114                 >>> from Crypto.Util.RFC1751 import english_to_key
4115                 >>> english_to_key('RAM LOIS GOAD CREW CARE HIT')
4116                 b'66666666'
4117
4118              Parameters
4119                     s  (string)  --  the  string  with the words separated by
4120                     whitespace; the number of words must be a multiple of 6.
4121
4122              Returns
4123                     A byte string.
4124
4125       Crypto.Util.RFC1751.key_to_english(key)
4126              Transform an arbitrary key  into  a  string  containing  English
4127              words.
4128
4129              Example:
4130
4131                 >>> from Crypto.Util.RFC1751 import key_to_english
4132                 >>> key_to_english(b'66666666')
4133                 'RAM LOIS GOAD CREW CARE HIT'
4134
4135              Parameters
4136                     key  (byte string) -- The key to convert. Its length must
4137                     be a multiple of 8.
4138
4139              Returns
4140                     A string of English words.
4141
4142   Crypto.Util.strxor module
4143       Fast XOR for byte strings.
4144
4145       Crypto.Util.strxor.strxor(term1, term2, output=None)
4146              XOR two byte strings.
4147
4148              Parameters
4149
4150term1 (bytes/bytearray/memoryview) -- The first term of
4151                       the XOR operation.
4152
4153term2  (bytes/bytearray/memoryview)  -- The second term
4154                       of the XOR operation.
4155
4156output (bytearray/memoryview) -- The location where the
4157                       result  must be written to.  If None, the result is re‐
4158                       turned.
4159
4160              Return If output is None, a new bytes string  with  the  result.
4161                     Otherwise None.
4162
4163       Crypto.Util.strxor.strxor_c(term, c, output=None)
4164              XOR a byte string with a repeated sequence of characters.
4165
4166              Parameters
4167
4168term  (bytes/bytearray/memoryview) -- The first term of
4169                       the XOR operation.
4170
4171c (bytes) -- The byte that makes up the second term  of
4172                       the XOR operation.
4173
4174output  (None  or bytearray/memoryview) -- If not None,
4175                       the location where the result is stored into.
4176
4177              Returns
4178                     If output is None, a new bytes string  with  the  result.
4179                     Otherwise None.
4180
4181   Crypto.Util.Counter module
4182       Richer counter functions for CTR cipher mode.
4183
4184       CTR is a mode of operation for block ciphers.
4185
4186       The  plaintext  is  broken up in blocks and each block is XOR-ed with a
4187       keystream to obtain the ciphertext.  The keystream is produced  by  the
4188       encryption  of  a sequence of counter blocks, which all need to be dif‐
4189       ferent to avoid repetitions in the keystream. Counter blocks don't need
4190       to be secret.
4191
4192       The  most  straightforward  approach is to include a counter field, and
4193       increment it by one within each subsequent counter block.
4194
4195       The new() function at the module level under Crypto.Cipher instantiates
4196       a  new  CTR cipher object for the relevant base algorithm.  Its parame‐
4197       ters allow you define a counter block with a fixed structure:
4198
4199       • an optional, fixed prefix
4200
4201       • the counter field encoded in big endian mode
4202
4203       The length of the two components can vary, but together they must be as
4204       large as the block size (e.g. 16 bytes for AES).
4205
4206       Alternatively,  the  counter  parameter  can  be used to pass a counter
4207       block    object    (created    in    advance    with    the    function
4208       Crypto.Util.Counter.new()) for a more complex composition:
4209
4210       • an optional, fixed prefix
4211
4212       • the counter field, encoded in big endian or little endian mode
4213
4214       • an optional, fixed suffix
4215
4216       As before, the total length must match the block size.
4217
4218       The counter blocks with a big endian counter will look like this:
4219         [image]
4220
4221       The counter blocks with a little endian counter will look like this:
4222         [image]
4223
4224       Example of AES-CTR encryption with custom counter:
4225
4226          from Crypto.Cipher import AES
4227          from Crypto.Util import Counter
4228          from Crypto import Random
4229
4230          nonce = Random.get_random_bytes(4)
4231          ctr = Counter.new(64, prefix=nonce, suffix=b'ABCD', little_endian=True, initial_value=10)
4232          key = b'AES-128 symm key'
4233          plaintext = b'X'*1000000
4234          cipher = AES.new(key, AES.MODE_CTR, counter=ctr)
4235          ciphertext = cipher.encrypt(plaintext)
4236
4237       Crypto.Util.Counter.new(nbits, prefix=b'', suffix=b'', initial_value=1,
4238       little_endian=False, allow_wraparound=False)
4239              Create a stateful counter block function suitable  for  CTR  en‐
4240              cryption modes.
4241
4242              Each  call to the function returns the next counter block.  Each
4243              counter block is made up by three parts:
4244
4245                             ┌───────┬───────────────┬─────────┐
4246                             │prefix │ counter value │ postfix │
4247                             └───────┴───────────────┴─────────┘
4248
4249              The counter value is incremented by 1 at each call.
4250
4251              Parameters
4252
4253nbits (integer) -- Length of the desired counter value,
4254                       in bits. It must be a multiple of 8.
4255
4256prefix  (byte  string)  --  The  constant prefix of the
4257                       counter block. By default, no prefix is used.
4258
4259suffix (byte string) -- The  constant  postfix  of  the
4260                       counter block. By default, no suffix is used.
4261
4262initial_value  (integer)  --  The  initial value of the
4263                       counter. Default value is 1.  Its length in  bits  must
4264                       not exceed the argument nbits.
4265
4266little_endian  (boolean) -- If True, the counter number
4267                       will be encoded in little endian format.  If False (de‐
4268                       fault), in big endian format.
4269
4270allow_wraparound  (boolean)  --  This  parameter is ig‐
4271                       nored.
4272
4273              Returns
4274                     An object that can be passed with the  counter  parameter
4275                     to a CTR mode cipher.
4276
4277              It  must  hold that len(prefix) + nbits//8 + len(suffix) matches
4278              the block size of the underlying block cipher.
4279
4280   Crypto.Util.number module
4281       Crypto.Util.number.GCD(x, y)
4282              Greatest Common Denominator of x and y.
4283
4284       Crypto.Util.number.bytes_to_long(s)
4285              Convert a byte string to a long integer (big endian).
4286
4287              In Python 3.2+, use the native method instead:
4288
4289                 >>> int.from_bytes(s, 'big')
4290
4291              For instance:
4292
4293                 >>> int.from_bytes(b'P', 'big')
4294                 80
4295
4296              This is (essentially) the inverse of long_to_bytes().
4297
4298       Crypto.Util.number.ceil_div(n, d)
4299              Return ceil(n/d), that is, the smallest integer r such that  r*d
4300              >= n
4301
4302       Crypto.Util.number.getPrime(N, randfunc=None)
4303              Return a random N-bit prime number.
4304
4305              If randfunc is omitted, then Random.get_random_bytes() is used.
4306
4307       Crypto.Util.number.getRandomInteger(N, randfunc=None)
4308              Return a random number at most N bits long.
4309
4310              If randfunc is omitted, then Random.get_random_bytes() is used.
4311
4312              Deprecated  since version 3.0: This function is for internal use
4313              only  and  may  be  renamed  or  removed  in  the  future.   Use
4314              Crypto.Random.random.getrandbits() instead.
4315
4316
4317       Crypto.Util.number.getRandomNBitInteger(N, randfunc=None)
4318              Return a random number with exactly N-bits, i.e. a random number
4319              between 2**(N-1) and (2**N)-1.
4320
4321              If randfunc is omitted, then Random.get_random_bytes() is used.
4322
4323              Deprecated since version 3.0: This function is for internal  use
4324              only and may be renamed or removed in the future.
4325
4326
4327       Crypto.Util.number.getRandomRange(a, b, randfunc=None)
4328              Return a random number n so that a <= n < b.
4329
4330              If randfunc is omitted, then Random.get_random_bytes() is used.
4331
4332              Deprecated  since version 3.0: This function is for internal use
4333              only  and  may  be  renamed  or  removed  in  the  future.   Use
4334              Crypto.Random.random.randrange() instead.
4335
4336
4337       Crypto.Util.number.getStrongPrime(N,   e=0,  false_positive_prob=1e-06,
4338       randfunc=None)
4339              Return a random strong N-bit prime number.  In this  context,  p
4340              is  a  strong prime if p-1 and p+1 have at least one large prime
4341              factor.
4342
4343              Parameters
4344
4345N (integer) -- the exact length of  the  strong  prime.
4346                       It must be a multiple of 128 and > 512.
4347
4348e  (integer)  -- if provided, the returned prime (minus
4349                       1) will be coprime to e and thus suitable for RSA where
4350                       e is the public exponent.
4351
4352false_positive_prob  (float)  -- The statistical proba‐
4353                       bility for the result not to be actually  a  prime.  It
4354                       defaults  to 10-6.  Note that the real probability of a
4355                       false-positive is far less. This is just the mathemati‐
4356                       cally provable limit.
4357
4358randfunc  (callable) -- A function that takes a parame‐
4359                       ter N and that returns a random  byte  string  of  such
4360                       length.   If  omitted, Crypto.Random.get_random_bytes()
4361                       is used.
4362
4363              Returns
4364                     The new strong prime.
4365
4366              Deprecated since version 3.0: This function is for internal  use
4367              only and may be renamed or removed in the future.
4368
4369
4370       Crypto.Util.number.inverse(u, v)
4371              The inverse of u mod v.
4372
4373       Crypto.Util.number.isPrime(N, false_positive_prob=1e-06, randfunc=None)
4374              Test if a number N is a prime.
4375
4376              Parameters
4377
4378false_positive_prob  (float)  -- The statistical proba‐
4379                       bility for the result not to be actually  a  prime.  It
4380                       defaults  to 10-6.  Note that the real probability of a
4381                       false-positive is far less.  This is just the mathemat‐
4382                       ically provable limit.
4383
4384randfunc  (callable) -- A function that takes a parame‐
4385                       ter N and that returns a random  byte  string  of  such
4386                       length.   If  omitted, Crypto.Random.get_random_bytes()
4387                       is used.
4388
4389              Returns
4390                     True is the input is indeed prime.
4391
4392       Crypto.Util.number.long_to_bytes(n, blocksize=0)
4393              Convert an integer to a byte string.
4394
4395              In Python 3.2+, use the native method instead:
4396
4397                 >>> n.to_bytes(blocksize, 'big')
4398
4399              For instance:
4400
4401                 >>> n = 80
4402                 >>> n.to_bytes(2, 'big')
4403                 b'P'
4404
4405              If the optional blocksize is provided and greater than zero, the
4406              byte  string  is padded with binary zeros (on the front) so that
4407              the total length of the output is a multiple of blocksize.
4408
4409              If blocksize is zero or not provided, the byte string will be of
4410              minimal length.
4411
4412       Crypto.Util.number.size(N)
4413              Returns the size of the number N in bits.
4414
4415       All  cryptographic  functionalities are organized in sub-packages; each
4416       sub-package is dedicated to solving a specific class of problems.
4417
4418                   ┌─────────────────┬────────────────────────────┐
4419                   │Package          │ Description                │
4420                   ├─────────────────┼────────────────────────────┤
4421                   │Crypto.Cipher    │ Modules   for   protecting │
4422                   │                 │ confidentiality  that  is, │
4423                   │                 │ for  encrypting  and   de‐ │
4424                   │                 │ crypting   data  (example: │
4425                   │                 │ AES).                      │
4426                   ├─────────────────┼────────────────────────────┤
4427                   │Crypto.Signature │ Modules for  assuring  au‐ 
4428                   │                 │ thenticity,  that  is, for │
4429                   │                 │ creating   and   verifying │
4430                   │                 │ digital signatures of mes‐ │
4431                   │                 │ sages   (example:   PKCS#1 │
4432                   │                 │ v1.5).                     │
4433                   ├─────────────────┼────────────────────────────┤
4434                   │Crypto.Hash      │ Modules for creating cryp‐ │
4435                   │                 │ tographic  digests  (exam‐ │
4436                   │                 │ ple: SHA-256).             │
4437                   ├─────────────────┼────────────────────────────┤
4438                   │Crypto.PublicKey │ Modules   for  generating, │
4439                   │                 │ exporting   or   importing │
4440                   │                 │ public  keys (example: RSA │
4441                   │                 │ or ECC).                   │
4442                   ├─────────────────┼────────────────────────────┤
4443                   │Crypto.Protocol  │ Modules for faciliting se‐ │
4444                   │                 │ cure   communications  be‐ │
4445                   │                 │ tween  parties,  in   most │
4446                   │                 │ cases  by leveraging cryp‐ │
4447                   │                 │ tograpic  primitives  from │
4448                   │                 │ other   modules  (example: │
4449                   │                 │ Shamir's  Secret   Sharing │
4450                   │                 │ scheme).                   │
4451                   ├─────────────────┼────────────────────────────┤
4452                   │Crypto.IO        │ Modules  for  dealing with │
4453                   │                 │ encodings  commonly   used │
4454                   │                 │ for   cryptographic   data │
4455                   │                 │ (example: PEM).            │
4456                   └─────────────────┴────────────────────────────┘
4457
4458
4459                   │Crypto.Random    │ Modules   for   generating │
4460                   │                 │ random data.               │
4461                   ├─────────────────┼────────────────────────────┤
4462                   │Crypto.Util      │ General  purpose  routines │
4463                   │                 │ (example:  XOR  for   byte │
4464                   │                 │ strings).                  │
4465                   └─────────────────┴────────────────────────────┘
4466
4467       In  certain cases, there is some overlap between these categories.  For
4468       instance, authenticity  is  also  provided  by  Message  Authentication
4469       Codes, and some can be built using digests, so they are included in the
4470       Crypto.Hash package (example: HMAC).  Also,  cryptographers  have  over
4471       time  realized  that encryption without authentication is often of lim‐
4472       ited value so recent ciphers found in the Crypto.Cipher  package  embed
4473       it (example: GCM).
4474
4475       PyCryptodome strives to maintain strong backward compatibility with the
4476       old PyCrypto's API (except for those few cases where that is harmful to
4477       security) so a few modules don't appear where they should (example: the
4478       ASN.1 module is under Crypto.Util as opposed to Crypto.IO).
4479

EXAMPLES

4481   Encrypt data with AES
4482       The following code generates a new AES128 key and encrypts a  piece  of
4483       data  into  a file.  We use the EAX mode because it allows the receiver
4484       to detect any unauthorized modification (similarly, we could have  used
4485       other authenticated encryption modes like GCM, CCM or SIV).
4486
4487          from Crypto.Cipher import AES
4488          from Crypto.Random import get_random_bytes
4489
4490          key = get_random_bytes(16)
4491          cipher = AES.new(key, AES.MODE_EAX)
4492          ciphertext, tag = cipher.encrypt_and_digest(data)
4493
4494          file_out = open("encrypted.bin", "wb")
4495          [ file_out.write(x) for x in (cipher.nonce, tag, ciphertext) ]
4496          file_out.close()
4497
4498       At the other end, the receiver can securely load the piece of data back
4499       (if they know the key!).  Note that the code generates a ValueError ex‐
4500       ception when tampering is detected.
4501
4502          from Crypto.Cipher import AES
4503
4504          file_in = open("encrypted.bin", "rb")
4505          nonce, tag, ciphertext = [ file_in.read(x) for x in (16, 16, -1) ]
4506
4507          # let's assume that the key is somehow available again
4508          cipher = AES.new(key, AES.MODE_EAX, nonce)
4509          data = cipher.decrypt_and_verify(ciphertext, tag)
4510
4511   Generate an RSA key
4512       The  following  code generates a new RSA key pair (secret) and saves it
4513       into a file, protected by a password.  We use the scrypt key derivation
4514       function to thwart dictionary attacks.  At the end, the code prints our
4515       the RSA public key in ASCII/PEM format:
4516
4517          from Crypto.PublicKey import RSA
4518
4519          secret_code = "Unguessable"
4520          key = RSA.generate(2048)
4521          encrypted_key = key.export_key(passphrase=secret_code, pkcs=8,
4522                                        protection="scryptAndAES128-CBC")
4523
4524          file_out = open("rsa_key.bin", "wb")
4525          file_out.write(encrypted_key)
4526          file_out.close()
4527
4528          print(key.publickey().export_key())
4529
4530       The following code reads the private RSA key back in, and  then  prints
4531       again the public key:
4532
4533          from Crypto.PublicKey import RSA
4534
4535          secret_code = "Unguessable"
4536          encoded_key = open("rsa_key.bin", "rb").read()
4537          key = RSA.import_key(encoded_key, passphrase=secret_code)
4538
4539          print(key.publickey().export_key())
4540
4541   Generate public key and private key
4542       The following code generates public key stored in receiver.pem and pri‐
4543       vate key stored in private.pem. These files will be used in  the  exam‐
4544       ples  below.  Every time, it generates different public key and private
4545       key pair.
4546
4547          from Crypto.PublicKey import RSA
4548
4549          key = RSA.generate(2048)
4550          private_key = key.export_key()
4551          file_out = open("private.pem", "wb")
4552          file_out.write(private_key)
4553          file_out.close()
4554
4555          public_key = key.publickey().export_key()
4556          file_out = open("receiver.pem", "wb")
4557          file_out.write(public_key)
4558          file_out.close()
4559
4560   Encrypt data with RSA
4561       The following code encrypts a piece of data for a receiver we have  the
4562       RSA  public  key of.  The RSA public key is stored in a file called re‐
4563       ceiver.pem.
4564
4565       Since we want to be able to encrypt an arbitrary amount of data, we use
4566       a hybrid encryption scheme.  We use RSA with PKCS#1 OAEP for asymmetric
4567       encryption of an AES session key.  The session key can then be used  to
4568       encrypt all the actual data.
4569
4570       As  in  the  first  example,  we use the EAX mode to allow detection of
4571       unauthorized modifications.
4572
4573          from Crypto.PublicKey import RSA
4574          from Crypto.Random import get_random_bytes
4575          from Crypto.Cipher import AES, PKCS1_OAEP
4576
4577          data = "I met aliens in UFO. Here is the map.".encode("utf-8")
4578          file_out = open("encrypted_data.bin", "wb")
4579
4580          recipient_key = RSA.import_key(open("receiver.pem").read())
4581          session_key = get_random_bytes(16)
4582
4583          # Encrypt the session key with the public RSA key
4584          cipher_rsa = PKCS1_OAEP.new(recipient_key)
4585          enc_session_key = cipher_rsa.encrypt(session_key)
4586
4587          # Encrypt the data with the AES session key
4588          cipher_aes = AES.new(session_key, AES.MODE_EAX)
4589          ciphertext, tag = cipher_aes.encrypt_and_digest(data)
4590          [ file_out.write(x) for x in (enc_session_key, cipher_aes.nonce, tag, ciphertext) ]
4591          file_out.close()
4592
4593       The receiver has the private RSA key. They will use it to  decrypt  the
4594       session key first, and with that the rest of the file:
4595
4596          from Crypto.PublicKey import RSA
4597          from Crypto.Cipher import AES, PKCS1_OAEP
4598
4599          file_in = open("encrypted_data.bin", "rb")
4600
4601          private_key = RSA.import_key(open("private.pem").read())
4602
4603          enc_session_key, nonce, tag, ciphertext = \
4604             [ file_in.read(x) for x in (private_key.size_in_bytes(), 16, 16, -1) ]
4605
4606          # Decrypt the session key with the private RSA key
4607          cipher_rsa = PKCS1_OAEP.new(private_key)
4608          session_key = cipher_rsa.decrypt(enc_session_key)
4609
4610          # Decrypt the data with the AES session key
4611          cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce)
4612          data = cipher_aes.decrypt_and_verify(ciphertext, tag)
4613          print(data.decode("utf-8"))
4614

FREQUENTLY ASKED QUESTIONS

4616   Is CTR cipher mode compatible with Java?
4617       Yes. When you instantiate your AES cipher in Java:
4618
4619          Cipher  cipher = Cipher.getInstance("AES/CTR/NoPadding");
4620
4621          SecretKeySpec keySpec = new SecretKeySpec(new byte[16], "AES");
4622          IvParameterSpec ivSpec = new IvParameterSpec(new byte[16]);
4623
4624          cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
4625
4626       You  are  effectively  using  ctr_mode without a fixed nonce and with a
4627       128-bit big endian counter starting at 0.  The counter will wrap around
4628       only after 2¹²⁸ blocks.
4629
4630       You can replicate the same keystream in PyCryptodome with:
4631
4632          ivSpec = b'\x00' * 16
4633          ctr = AES.new(keySpec, AES.MODE_CTR, initial_value=ivSpec, nonce=b'')
4634
4635   Are RSASSA-PSS signatures compatible with Java or OpenSSL?
4636       Yes.  For Java, you must consider that by default the mask is generated
4637       by MGF1 with SHA-1 (regardless of how you hash  the  message)  and  the
4638       salt is 20 bytes long.
4639
4640       If  you  want to use another algorithm or another salt length, you must
4641       instantiate a PSSParameterSpec object, for instance:
4642
4643          Signature ss = Signature.getInstance("SHA256withRSA/PSS");
4644          AlgorithmParameters pss1 = ss.getParameters();
4645          PSSParameterSpec pssParameterSpec = new PSSParameterSpec("SHA-256", "MGF1", new MGF1ParameterSpec("SHA-256"), 32, 0xBC);
4646          ss.setParameter(spec1);
4647
4648       On the other hand, a quirk of OpenSSL (and of a  few  other  libraries,
4649       especially  if  they  are wrappers to OpenSSL) is that the default salt
4650       length is maximized, and it does not match in size the  digest  applied
4651       to  the message, as recommended in RFC8017.  In PyCryptodome, you maxi‐
4652       mize the salt length with:
4653
4654          key = RSA.import_key(open('privkey.der').read())
4655          h = SHA256.new(message)
4656          salt_bytes = key.size_in_bytes() - h.digest_size - 2
4657          signature = pss.new(key, salt_bytes=salt_bytes).sign(h)
4658
4659   Why do I get the error No module named Crypto on Windows?
4660       Check the directory where Python packages are installed, like:
4661
4662          /path/to/python/Lib/site-packages/
4663
4664       You might find a directory named  crypto,  with  all  the  PyCryptodome
4665       files in it.
4666
4667       The  most  likely  cause  is described here and you can fix the problem
4668       with:
4669
4670          pip uninstall crypto
4671          pip uninstall pycryptodome
4672          pip install pycryptodome
4673
4674       The root cause is that, in the past, you most likely have installed  an
4675       unrelated  but  similarly named package called crypto, which happens to
4676       operate under the namespace crypto.
4677
4678       The Windows filesystem is case-insensitive so crypto and Crypto are ef‐
4679       fectively considered the same thing.  When you subsequently install py‐
4680       cryptodome, pip finds that a directory named with the target  namespace
4681       already  exists  (under  the  rules  of the underlying filesystem), and
4682       therefore installs all the sub-packages of pycryptodome in it.  This is
4683       probably  a  reasonable  behavior, if it wasn't that pip does not issue
4684       any warning even if it could detect the issue.
4685
4686   Why does strxor raise TypeError: argument 2 must be bytes, not bytearray?
4687       Most probably you have installed both the pycryptodome and the old  py‐
4688       crypto packages.
4689
4690       Run pip uninstall pycrypto and try again.
4691
4692       The  old  PyCrypto shipped with a strxor module written as a native li‐
4693       brary (.so or .dll file).  If you install pycryptodome, the old  native
4694       module  will  still  take  priority  over the new Python extension that
4695       comes in the latter.
4696

CONTRIBUTE AND SUPPORT

4698       • Do not be afraid to contribute with small and  apparently  insignifi‐
4699         cant improvements like correction to typos. Every change counts.
4700
4701       • Read  carefully the license of PyCryptodome. By submitting your code,
4702         you acknowledge that you accept to release it according  to  the  BSD
4703         2-clause license.
4704
4705       • You  must disclaim which parts of your code in your contribution were
4706         partially copied or derived from an existing source. Ensure that  the
4707         original is licensed in a way compatible to the BSD 2-clause license.
4708
4709       • You  can  propose  changes in any way you find most convenient.  How‐
4710         ever, the preferred approach is to:
4711
4712         • Clone the main repository on GitHub.
4713
4714         • Create a branch and modify the code.
4715
4716         • Send a pull request upstream with a meaningful description.
4717
4718       • Provide tests (in Crypto.SelfTest) along with code. If you fix a  bug
4719         add  a  test  that  fails in the current version and passes with your
4720         change.
4721
4722       • If your change breaks backward compatibility, highlight  it  and  in‐
4723         clude a justification.
4724
4725       • Ensure that your code complies to PEP8 and PEP257.
4726
4727       • If  you add or modify a public interface, make sure the relevant type
4728         stubs remain up to date.
4729
4730       • Ensure that your code does not use constructs or includes modules not
4731         present in Python 2.6.
4732
4733       • Add a short summary of the change to the file Changelog.rst.
4734
4735       • Add your name to the list of contributors in the file AUTHORS.rst.
4736
4737       The PyCryptodome mailing list is hosted on Google Groups.  You can mail
4738       any comment or question to pycryptodome@googlegroups.com.
4739
4740       Bug reports can be filed on the GitHub tracker.
4741

FUTURE PLANS

4743       Future releases will include:
4744
4745       • Update Crypto.Signature.DSS to FIPS 186-4
4746
4747       • Make all hash objects non-copyable and immutable after the first  di‐
4748         gest
4749
4750       • Add alias 'segment_bits' to parameter 'segment_size' for CFB
4751
4752       • Coverage testing
4753
4754       • Implement AES with bitslicing
4755
4756       • Add unit tests for PEM I/O
4757
4758       • Move old ciphers into a Museum submodule
4759
4760       • Add more ECC curves
4761
4762       • Import/export of ECC keys with compressed points
4763
4764
4765
4766         Add algorithms:
4767
4768                • Elliptic Curves (ECIES, ECDH)
4769
4770                • Camellia, GOST
4771
4772                • Diffie-Hellman
4773
4774                • bcrypt
4775
4776                • argon2
4777
4778                • SRP
4779
4780
4781
4782         Add more key management:
4783
4784                • Export/import of DSA domain parameters
4785
4786                • JWK
4787
4788       • Add support for CMS/PKCS#7
4789
4790       • Add support for RNG backed by PKCS#11 and/or KMIP
4791
4792       • Add support for Format-Preserving Encryption
4793
4794       • Remove dependency on libtomcrypto headers
4795
4796       • Speed up (T)DES with a bitsliced implementation
4797
4798       • Run lint on the C code
4799
4800       • Add (minimal) support for PGP
4801
4802       • Add (minimal) support for PKIX / X.509
4803

CHANGELOG

4805   3.10.1 (X February 2021)
4806   Other changes
4807       • Python 3 wheels use abi3 ABI tag.
4808
4809       • Remove Appveyor CI.
4810
4811   3.10.0 (6 February 2021)
4812   Resolved issues
4813       • Fixed a potential memory leak when initializing block ciphers.
4814
4815       • GH#466:  Crypto.Math.miller_rabin_test()  was  still using the system
4816         random source and not the one provided as parameter.
4817
4818       • GH#469: RSA objects have the method public_key()  like  ECC  objects.
4819         The  old  method publickey() is still available for backward compati‐
4820         bility.
4821
4822       • GH#476: Crypto.Util.Padding.unpad() was raising an  incorrect  excep‐
4823         tion in case of zero-length inputs. Thanks to Captainowie.
4824
4825       • GH#491: better exception message when Counter.new() is called with an
4826         integer initial_value than doesn't fit into nbits bits.
4827
4828       • GH#496: added missing  block_size  member  for  ECB  cipher  objects.
4829         Thanks to willem.
4830
4831       • GH#500:  nonce  member of an XChaCha20 cipher object was not matching
4832         the original nonce.  Thanks to Charles Machalow.
4833
4834   Other changes
4835       • The bulk of the test vectors have been moved to the separate  package
4836         pycryptodome-test-vectors.  As  result, packages pycryptodome and py‐
4837         cryptodomex become significantly smaller (from 14MB to 3MB).
4838
4839       • Moved CI tests and build service from Travis CI to GitHub Actions.
4840
4841   Breaks in compatibility
4842       • Drop support for Python 2.6 and 3.4.
4843
4844   3.9.9 (2 November 2020)
4845   Resolved issues
4846       • GH#435: Fixed Crypto.Util.number.size for negative numbers.
4847
4848   New features
4849       • Build Python 3.9 wheels on Windows.
4850
4851   3.9.8 (23 June 2020)
4852   Resolved issues
4853       • GH#426: The Shamir's secret sharing implementation  is  not  actually
4854         compatible with ssss.  Added an optional parameter to enable interop‐
4855         erability.
4856
4857       • GH#427: Skip altogether loading of gmp.dll on Windows.
4858
4859       • GH#420: Fix incorrect CFB decryption when the input  and  the  output
4860         are the same buffer.
4861
4862   New features
4863       • Speed up Shamir's secret sharing routines. Thanks to ncarve.
4864
4865   3.9.7 (20 February 2020)
4866   Resolved issues
4867       • GH#381:  Make  notarization possible again on OS X when using wheels.
4868         Thanks to Colin Atkinson.
4869
4870   3.9.6 (2 February 2020)
4871   Resolved issues
4872       • Fix building of wheels for OS X by explicitly setting  sysroot  loca‐
4873         tion.
4874
4875   3.9.5 (1 February 2020)
4876   Resolved issues
4877       • RSA OAEP decryption was not verifying that all PS bytes are zero.
4878
4879       • GH#372:  fixed  memory  leak for operations that use memoryviews when
4880         cffi is not installed.
4881
4882       • Fixed wrong ASN.1 OID for HMAC-SHA512 in PBE2.
4883
4884   New features
4885       • Updated Wycheproof test vectors to version 0.8r12.
4886
4887   3.9.4 (18 November 2019)
4888   Resolved issues
4889       • GH#341: Prevent key_to_english from creating invalid  data  when  fed
4890         with keys of length not multiple of 8. Thanks to vstoykovbg.
4891
4892       • GH#347:  Fix  blocking RSA signing/decryption when key has very small
4893         factor.  Thanks to Martijn Pieters.
4894
4895   3.9.3 (12 November 2019)
4896   Resolved issues
4897       • GH#308: Align stack of  functions  using  SSE2  intrinsics  to  avoid
4898         crashes, when compiled with gcc on 32-bit x86 platforms.
4899
4900   3.9.2 (10 November 2019)
4901   New features
4902       • Add Python 3.8 wheels for Mac.
4903
4904   Resolved issues
4905       • GH#308: Avoid allocating arrays of __m128i on the stack, to cope with
4906         buggy compilers.
4907
4908       • GH#322: Remove blanket -O3 optimization for gcc and  clang,  to  cope
4909         with buggy compilers.
4910
4911       • GH#337: Fix typing stubs for signatures.
4912
4913       • GH#338: Deal with gcc installations that don't have x86intrin.h.
4914
4915   3.9.1 (1 November 2019)
4916   New features
4917       • Add Python 3.8 wheels for Linux and Windows.
4918
4919   Resolved issues
4920       • GH#328: minor speed-up when importing RSA.
4921
4922   3.9.0 (27 August 2019)
4923   New features
4924       • Add support for loading PEM files encrypted with AES256-CBC.
4925
4926       • Add support for XChaCha20 and XChaCha20-Poly1305 ciphers.
4927
4928       • Add   support  for  bcrypt  key  derivation  function  (Crypto.Proto‐
4929         col.KDF.bcrypt).
4930
4931       • Add support for left multiplication of an EC point by a scalar.
4932
4933       • Add support for importing ECC and RSA keys in the new OpenSSH format.
4934
4935   Resolved issues
4936       • GH#312: it was not possible to invert an EC point anymore.
4937
4938       • GH#316: fix printing of DSA keys.
4939
4940       • GH#317: DSA.generate() was not always using the randfunc input.
4941
4942       • GH#285: the MD2 hash had block size of 64 bytes instead of 16; as re‐
4943         sult the HMAC construction gave incorrect results.
4944
4945   3.8.2 (30 May 2019)
4946   Resolved issues
4947       • GH#291: fix strict aliasing problem, emerged with GCC 9.1.
4948
4949   3.8.1 (4 April 2019)
4950   New features
4951       • Add  support  for  loading  PEM  files  encrypted with AES192-CBC and
4952         AES256-GCM.
4953
4954       • When importing ECC keys in PEM format, ignore the redundant EC PARAMS
4955         section that was included by certain openssl commands.
4956
4957   Resolved issues
4958repr() did not work for ECC.EccKey objects.
4959
4960       • Fix  installation  in  development mode (setup install develop or pip
4961         install -e .).
4962
4963       • Minimal length for Blowfish cipher is 32 bits, not 40 bits.
4964
4965       • Various updates to docs.
4966
4967   3.8.0 (23 March 2019)
4968   New features
4969       • Speed-up ECC performance. ECDSA is 33 times faster on the NIST  P-256
4970         curve.
4971
4972       • Added support for NIST P-384 and P-521 curves.
4973
4974EccKey has new methods size_in_bits() and size_in_bytes().
4975
4976       • Support  HMAC-SHA224,  HMAC-SHA256,  HMAC-SHA384,  and HMAC-SHA512 in
4977         PBE2/PBKDF2.
4978
4979   Resolved issues
4980       • DER objects were not rejected if their length  field  had  a  leading
4981         zero.
4982
4983       • Allow legacy RC2 ciphers to have 40-bit keys.
4984
4985       • ASN.1 Object IDs did not allow the value 0 in the path.
4986
4987   Breaks in compatibility
4988point_at_infinity()   becomes  an  instance  method  for  Crypto.Pub‐
4989         licKey.ECC.EccKey, from a static one.
4990
4991   3.7.3 (19 January 2019)
4992   Resolved issues
4993       • GH#258: False positive on PSS  signatures  when  externally  provided
4994         salt is too long.
4995
4996       • Include type stub files for Crypto.IO and Crypto.Util.
4997
4998   3.7.2 (26 November 2018)
4999   Resolved issues
5000       • GH#242: Fixed compilation problem on ARM platforms.
5001
5002   3.7.1 (25 November 2018)
5003   New features
5004       • Added  type stubs to enable static type checking with mypy. Thanks to
5005         Michael Nix.
5006
5007       • New update_after_digest flag for CMAC.
5008
5009   Resolved issues
5010       • GH#232: Fixed problem with gcc 4.x when compiling ghash_clmul.c.
5011
5012       • GH#238: Incorrect digest value produced by CMAC after cloning the ob‐
5013         ject.
5014
5015       • Method  update() of an EAX cipher object was returning the underlying
5016         CMAC object, instead of the EAX object itself.
5017
5018       • Method update() of a CMAC object was not throwing an exception  after
5019         the digest was computed (with digest() or verify()).
5020
5021   3.7.0 (27 October 2018)
5022   New features
5023       • Added support for Poly1305 MAC (with AES and ChaCha20 ciphers for key
5024         derivation).
5025
5026       • Added support for ChaCha20-Poly1305 AEAD cipher.
5027
5028       • New     parameter     output      for      Crypto.Util.strxor.strxor,
5029         Crypto.Util.strxor.strxor_c, encrypt and decrypt methods in symmetric
5030         ciphers (Crypto.Cipher package).  output is a pre-allocated buffer (a
5031         bytearray or a writeable memoryview) where the result must be stored.
5032         This requires less memory for very large payloads; it  is  also  more
5033         efficient when encrypting (or decrypting) several small payloads.
5034
5035   Resolved issues
5036       • GH#266:  AES-GCM hangs when processing more than 4GB at a time on x86
5037         with PCLMULQDQ instruction.
5038
5039   Breaks in compatibility
5040       • Drop support for Python 3.3.
5041
5042       • Remove   Crypto.Util.py3compat.unhexlify   and    Crypto.Util.py3com‐
5043         pat.hexlify.
5044
5045       • With  the old Python 2.6, use only ctypes (and not cffi) to interface
5046         to native code.
5047
5048   3.6.6 (17 August 2018)
5049   Resolved issues
5050       • GH#198: Fix vulnerability on AESNI ECB with payloads smaller than  16
5051         bytes (CVE-2018-15560).
5052
5053   3.6.5 (12 August 2018)
5054   Resolved issues
5055       • GH#187:  Fixed incorrect AES encryption/decryption with AES accelera‐
5056         tion on x86 due to gcc's optimization and strict aliasing rules.
5057
5058       • GH#188: More prime number candidates than necessary  where  discarded
5059         as  composite  due  to  the limited way D values were searched in the
5060         Lucas test.
5061
5062       • Fixed ResouceWarnings and DeprecationWarnings.
5063
5064       • Workaround    for    Python    3.7.0    bug     on     Windows     (‐
5065         https://bugs.python.org/issue34108).
5066
5067   3.6.4 (10 July 2018)
5068   New features
5069       • Build Python 3.7 wheels on Linux, Windows and Mac.
5070
5071   Resolved issues
5072       • GH#178: Rename _cpuid module to make upgrades more robust.
5073
5074       • More   meaningful  exceptions  in  case  of  mismatch  in  IV  length
5075         (CBC/OFB/CFB modes).
5076
5077       • Fix compilation issues on Solaris 10/11.
5078
5079   3.6.3 (21 June 2018)
5080   Resolved issues
5081       • GH#175: Fixed incorrect results for  CTR  encryption/decryption  with
5082         more than 8 blocks.
5083
5084   3.6.2 (19 June 2018)
5085   New features
5086       • ChaCha20  accepts 96 bit nonces (in addition to 64 bit nonces) as de‐
5087         fined in RFC7539.
5088
5089       • Accelerate AES-GCM on x86 using PCLMULQDQ instruction.
5090
5091       • Accelerate AES-ECB and AES-CTR on x86 by  pipelining  AESNI  instruc‐
5092         tions.
5093
5094       • As result of the two improvements above, on x86 (Broadwell):
5095
5096         • AES-ECB and AES-CTR are 3x faster
5097
5098         • AES-GCM is 9x faster
5099
5100   Resolved issues
5101       • On Windows, MPIR library was stilled pulled in if renamed to gmp.dll.
5102
5103   Breaks in compatibility
5104       • In  Crypto.Util.number,  functions  floor_div and exact_div have been
5105         removed. Also, ceil_div is limited to non-negative terms only.
5106
5107   3.6.1 (15 April 2018)
5108   New features
5109       • Added Google Wycheproof tests  (https://github.com/google/wycheproof)
5110         for RSA, DSA, ECDSA, GCM, SIV, EAX, CMAC.
5111
5112       • New parameter mac_len (length of MAC tag) for CMAC.
5113
5114   Resolved issues
5115       • In certain circumstances (at counter wrapping, which happens on aver‐
5116         age after 32 GB) AES GCM produced wrong ciphertexts.
5117
5118       • Method encrypt() of AES SIV cipher could  be  still  called,  whereas
5119         only encrypt_and_digest() is allowed.
5120
5121   3.6.0 (8 April 2018)
5122   New features
5123       • Introduced  export_key  and  deprecated exportKey for DSA and RSA key
5124         objects.
5125
5126       • Ciphers and hash functions accept memoryview objects in input.
5127
5128       • Added support for SHA-512/224 and SHA-512/256.
5129
5130   Resolved issues
5131       • Reintroduced Crypto.__version__ variable as in PyCrypto.
5132
5133       • Fixed compilation problem with MinGW.
5134
5135   3.5.1 (8 March 2018)
5136   Resolved issues
5137       • GH#142. Fix mismatch with declaration and definition of addmul128.
5138
5139   3.5.0 (7 March 2018)
5140   New features
5141       • Import and export of ECC curves in compressed form.
5142
5143       • The initial counter for a cipher in CTR mode can be a byte string (in
5144         addition to an integer).
5145
5146       • Faster  PBKDF2 for HMAC-based PRFs (at least 20x for short passwords,
5147         more for longer passwords). Thanks to Christian Heimes  for  pointing
5148         out the implementation was under-optimized.
5149
5150       • The salt for PBKDF2 can be either a string or bytes (GH#67).
5151
5152       • Ciphers  and hash functions accept data as bytearray, not just binary
5153         strings.
5154
5155       • The old SHA-1 and MD5 hash functions are available even when Python's
5156         own hashlib does not include them.
5157
5158   Resolved issues
5159       • Without  libgmp,  modular  exponentiation  (since  v3.4.8) crashed on
5160         32-bit big-endian systems.
5161
5162   Breaks in compatibility
5163       • Removed support for Python < 2.6.
5164
5165   3.4.12 (5 February 2018)
5166   Resolved issues
5167       • GH#129. pycryptodomex could only be installed via wheels.
5168
5169   3.4.11 (5 February 2018)
5170   Resolved issues
5171       • GH#121. the record list was still not  correct  due  to  PEP3147  and
5172         __pycache__ directories. Thanks again to John O'Brien.
5173
5174   3.4.10 (2 February 2018)
5175   Resolved issues
5176       • When  creating  ElGamal  keys, the generator wasn't a square residue:
5177         ElGamal encryption done with those keys cannot be  secure  under  the
5178         DDH assumption. Thanks to Weikeng Chen.
5179
5180   3.4.9 (1 February 2018)
5181   New features
5182       • More meaningful error messages while importing an ECC key.
5183
5184   Resolved issues
5185       • GH#123  and  #125. The SSE2 command line switch was not always passed
5186         on 32-bit x86 platforms.
5187
5188       • GH#121. The record list (--record) was not  always  correctly  filled
5189         for the pycryptodomex package. Thanks to John W. O'Brien.
5190
5191   3.4.8 (27 January 2018)
5192   New features
5193       • Added  a native extension in pure C for modular exponentiation, opti‐
5194         mized for SSE2 on x86.  In the process, we drop support for the arbi‐
5195         trary arithmetic library MPIR on Windows, which is painful to compile
5196         and deploy.  The custom  modular exponentiation is 130% (160%) slower
5197         on  an  Intel  CPU  in 32-bit (64-bit) mode, compared to MPIR. Still,
5198         that is much faster that CPython's own pow() function which  is  900%
5199         (855%) slower than MPIR. Support for the GMP library on Unix remains.
5200
5201       • Added support for manylinux wheels.
5202
5203       • Support for Python 3.7.
5204
5205   Resolved issues
5206       • The  DSA  parameter  'p' prime was created with 255 bits cleared (but
5207         still with the correct strength).
5208
5209       • GH#106. Not all docs were  included  in  the  tar  ball.   Thanks  to
5210         Christopher Hoskin.
5211
5212       • GH#109. ECDSA verification failed for DER encoded signatures.  Thanks
5213         to Alastair Houghton.
5214
5215       • Human-friendly messages for padding errors with ECB and CBC.
5216
5217   3.4.7 (26 August 2017)
5218   New features
5219       • API documentation is made with sphinx instead of epydoc.
5220
5221       • Start using importlib instead of imp where available.
5222
5223   Resolved issues
5224       • GH#82. Fixed PEM header for RSA/DSA public keys.
5225
5226   3.4.6 (18 May 2017)
5227   Resolved issues
5228       • GH#65. Keccak, SHA3, SHAKE and the seek  functionality  for  ChaCha20
5229         were  not  working  on  big  endian  machines.  Fixed. Thanks to Mike
5230         Gilbert.
5231
5232       • A few fixes in the documentation.
5233
5234   3.4.5 (6 February 2017)
5235   Resolved issues
5236       • The library can also be compiled using MinGW.
5237
5238   3.4.4 (1 February 2017)
5239   Resolved issues
5240       • Removed use of alloca().
5241
5242       • [Security] Removed implementation of deprecated "quick check" feature
5243         of PGP block cipher mode.
5244
5245       • Improved the performance of scrypt by converting some Python to C.
5246
5247   3.4.3 (17 October 2016)
5248   Resolved issues
5249       • Undefined warning was raised with libgmp version < 5
5250
5251       • Forgot inclusion of alloca.h
5252
5253       • Fixed a warning about type mismatch raised by recent versions of cffi
5254
5255   3.4.2 (8 March 2016)
5256   Resolved issues
5257       • Fix renaming of package for install command.
5258
5259   3.4.1 (21 February 2016)
5260   New features
5261       • Added option to install the library under the Cryptodome package (in‐
5262         stead of Crypto).
5263
5264   3.4 (7 February 2016)
5265   New features
5266       • Added Crypto.PublicKey.ECC module (NIST P-256 curve only),  including
5267         export/import of ECC keys.
5268
5269       • Added support for ECDSA (FIPS 186-3 and RFC6979).
5270
5271       • For CBC/CFB/OFB/CTR cipher objects, encrypt() and decrypt() cannot be
5272         intermixed.
5273
5274       • CBC/CFB/OFB, the cipher objects  have  both  IV  and  iv  attributes.
5275         new() accepts IV as well as iv as parameter.
5276
5277       • For CFB/OPENPGP cipher object, encrypt() and decrypt() do not require
5278         the plaintext or ciphertext pieces to have length multiple of the CFB
5279         segment size.
5280
5281       • Added  dedicated tests for all cipher modes, including NIST test vec‐
5282         tors
5283
5284       • CTR/CCM/EAX/GCM/SIV/Salsa20/ChaCha20 objects expose the nonce  attri‐
5285         bute.
5286
5287       • For  performance reasons, CCM cipher optionally accepted a pre-decla‐
5288         ration of the length of the associated data, but never checked if the
5289         actual  data  passed  to  the cipher really matched that length. Such
5290         check is now enforced.
5291
5292       • CTR cipher objects accept parameter nonce and possibly  initial_value
5293         in alternative to counter (which is deprecated).
5294
5295       • All  iv/IV  and  nonce parameters are optional. If not provided, they
5296         will be randomly generated (exception: nonce for CTR mode in case  of
5297         block sizes smaller than 16 bytes).
5298
5299       • Refactored ARC2 cipher.
5300
5301       • Added Crypto.Cipher.DES3.adjust_key_parity() function.
5302
5303       • Added  RSA.import_key  as  an  alias  to the deprecated RSA.importKey
5304         (same for the DSA module).
5305
5306       • Added size_in_bits() and size_in_bytes() methods to RsaKey.
5307
5308   Resolved issues
5309       • RSA key size is now returned correctly  in  RsaKey.__repr__()  method
5310         (kudos to hannesv).
5311
5312       • CTR  mode  does  not modify anymore counter parameter passed to new()
5313         method.
5314
5315       • CTR raises OverflowError instead of ValueError when the counter wraps
5316         around.
5317
5318       • PEM files with Windows newlines could not be imported.
5319
5320Crypto.IO.PEM and Crypto.IO.PKCS8 used to accept empty passphrases.
5321
5322       • GH#6:  NotImplementedError  now  raised for unsupported methods sign,
5323         verify, encrypt, decrypt, blind, unblind and size in objects  RsaKey,
5324         DsaKey, ElGamalKey.
5325
5326   Breaks in compatibility
5327       • Parameter segment_size cannot be 0 for the CFB mode.
5328
5329       • For  OCB ciphers, a final call without parameters to encrypt must end
5330         a sequence of calls to encrypt with data (similarly for decrypt).
5331
5332       • Key size for ARC2, ARC4 and Blowfish must be at least  40  bits  long
5333         (still very weak).
5334
5335       • DES3  (Triple DES module) does not allow keys that degenerate to Sin‐
5336         gle DES.
5337
5338       • Removed method getRandomNumber in Crypto.Util.number.
5339
5340       • Removed module Crypto.pct_warnings.
5341
5342       • Removed attribute Crypto.PublicKey.RSA.algorithmIdentifier.
5343
5344   3.3.1 (1 November 2015)
5345   New features
5346       • Opt-in for update() after digest() for SHA-3, keccak, BLAKE2 hashes
5347
5348   Resolved issues
5349       • Removed unused SHA-3 and keccak test vectors, therefore significantly
5350         reducing the package from 13MB to 3MB.
5351
5352   Breaks in compatibility
5353       • Removed method copy() from BLAKE2 hashes
5354
5355       • Removed  ability  to  update()  a BLAKE2 hash after the first call to
5356         (hex)digest()
5357
5358   3.3 (29 October 2015)
5359   New features
5360       • Windows wheels bundle the MPIR library
5361
5362       • Detection of faults occurring during secret RSA operations
5363
5364       • Detection of non-prime (weak) q value in DSA domain parameters
5365
5366       • Added original Keccak hash family (b=1600  only).   In  the  process,
5367         simplified the C code base for SHA-3.
5368
5369       • Added SHAKE128 and SHAKE256 (of SHA-3 family)
5370
5371   Resolved issues
5372       • GH#3: gcc 4.4.7 unhappy about double typedef
5373
5374   Breaks in compatibility
5375       • Removed method copy() from all SHA-3 hashes
5376
5377       • Removed  ability  to  update()  a  SHA-3 hash after the first call to
5378         (hex)digest()
5379
5380   3.2.1 (9 September 2015)
5381   New features
5382       • Windows wheels are automatically built on Appveyor
5383
5384   3.2 (6 September 2015)
5385   New features
5386       • Added hash functions BLAKE2b and BLAKE2s.
5387
5388       • Added stream cipher ChaCha20.
5389
5390       • Added OCB cipher mode.
5391
5392       • CMAC raises an exception whenever the message length is found  to  be
5393         too large and the chance of collisions not negligeable.
5394
5395       • New attribute oid for Hash objects with ASN.1 Object ID
5396
5397       • Added Crypto.Signature.pss and Crypto.Signature.pkcs1_15
5398
5399       • Added NIST test vectors (roughly 1200) for PKCS#1 v1.5 and PSS signa‐
5400         tures.
5401
5402   Resolved issues
5403       • tomcrypt_macros.h asm error #1
5404
5405   Breaks in compatibility
5406       • Removed keyword verify_x509_cert from module  method  importKey  (RSA
5407         and DSA).
5408
5409       • Reverted to original PyCrypto behavior of method verify in PKCS1_v1_5
5410         and PKCS1_PSS.
5411
5412   3.1 (15 March 2015)
5413   New features
5414       • Speed up execution of Public Key algorithms on PyPy, when  backed  by
5415         the Gnu Multiprecision (GMP) library.
5416
5417       • GMP headers and static libraries are not required anymore at the time
5418         PyCryptodome is built. Instead, the code will automatically  use  the
5419         GMP dynamic library (.so/.DLL) if found in the system at runtime.
5420
5421       • Reduced the amount of C code by almost 40% (4700 lines).  Modularized
5422         and simplified all code (C and Python) related to block ciphers.  Py‐
5423         cryptodome is now free of CPython extensions.
5424
5425       • Add support for CI in Windows via Appveyor.
5426
5427       • RSA and DSA key generation more closely follows FIPS 186-4 (though it
5428         is not 100% compliant).
5429
5430   Resolved issues
5431       • None
5432
5433   Breaks in compatibility
5434       • New dependency on ctypes with Python 2.4.
5435
5436       • The counter parameter of a CTR mode  cipher  must  be  generated  via
5437         Crypto.Util.Counter. It cannot be a generic callable anymore.
5438
5439       • Removed  the  Crypto.Random.Fortuna package (due to lack of test vec‐
5440         tors).
5441
5442       • Removed the Crypto.Hash.new function.
5443
5444       • The allow_wraparound parameter of Crypto.Util.Counter is ignored.  An
5445         exception is always generated if the counter is reused.
5446
5447DSA.generate,  RSA.generate  and  ElGamal.generate  do not accept the
5448         progress_func parameter anymore.
5449
5450       • Removed Crypto.PublicKey.RSA.RSAImplementation.
5451
5452       • Removed Crypto.PublicKey.DSA.DSAImplementation.
5453
5454       • Removed ambiguous method size() from RSA, DSA and ElGamal keys.
5455
5456   3.0 (24 June 2014)
5457   New features
5458       • Initial support for PyPy.
5459
5460       • SHA-3 hash family based on the April 2014 draft  of  FIPS  202.   See
5461         modules  Crypto.Hash.SHA3_224/256/384/512.   Initial  Keccak patch by
5462         Fabrizio Tarizzo.
5463
5464       • Salsa20 stream cipher. See module  Crypto.Cipher.Salsa20.   Patch  by
5465         Fabrizio Tarizzo.
5466
5467       • Colin   Percival's  scrypt  key  derivation  function  (Crypto.Proto‐
5468         col.KDF.scrypt).
5469
5470       • Proper interface to FIPS 186-3 DSA. See module Crypto.Signature.DSS.
5471
5472       • Deterministic DSA (RFC6979). Again, see Crypto.Signature.DSS.
5473
5474       • HMAC-based Extract-and-Expand key derivation function  (Crypto.Proto‐
5475         col.KDF.HKDF, RFC5869).
5476
5477       • Shamir's  Secret  Sharing  protocol,  compatible  with ssss (128 bits
5478         only).  See module Crypto.Protocol.SecretSharing.
5479
5480       • Ability to generate a DSA key given the domain parameters.
5481
5482       • Ability to test installation with a simple python -m Crypto.SelfTest.
5483
5484   Resolved issues
5485       • LP#1193521: mpz_powm_sec() (and Python) crashed when modulus was odd.
5486
5487       • Benchmarks work again (they broke when ECB stopped working if  an  IV
5488         was passed. Patch by Richard Mitchell.
5489
5490       • LP#1178485:  removed  some  catch-all  exception  handlers.  Patch by
5491         Richard Mitchell.
5492
5493       • LP#1209399: Removal of Python wrappers caused HMAC to  silently  pro‐
5494         duce the wrong data with SHA-2 algorithms.
5495
5496       • LP#1279231:  remove  dead  code  that  does  nothing in SHA-2 hashes.
5497         Patch by Richard Mitchell.
5498
5499       • LP#1327081: AESNI code accesses memory beyond buffer end.
5500
5501       • Stricter checks on ciphertext and plaintext  size  for  textbook  RSA
5502         (kudos to sharego).
5503
5504   Breaks in compatibility
5505       • Removed support for Python < 2.4.
5506
5507       • Removed  the  following  methods  from  all 3 public key object types
5508         (RSA, DSA, ElGamal):
5509
5510sign
5511
5512verify
5513
5514encrypt
5515
5516decrypt
5517
5518blind
5519
5520unblind
5521
5522         Code that uses such methods is doomed anyway. It should be fixed ASAP
5523         to  use  the  algorithms available in Crypto.Signature and Crypto.Ci‐
5524         pher.
5525
5526       • The 3 public key object types (RSA, DSA, ElGamal) are now unpickable.
5527
5528       • Symmetric ciphers do not have a default  mode  anymore  (used  to  be
5529         ECB).   An  expression like AES.new(key) will now fail. If ECB is the
5530         desired mode, one has to explicitly use AES.new(key, AES.MODE_ECB).
5531
5532       • Unsuccessful verification of a signature will now raise an  exception
5533         [reverted in 3.2].
5534
5535       • Removed the Crypto.Random.OSRNG package.
5536
5537       • Removed the Crypto.Util.winrandom module.
5538
5539       • Removed the Crypto.Random.randpool module.
5540
5541       • Removed the Crypto.Cipher.XOR module.
5542
5543       • Removed the Crypto.Protocol.AllOrNothing module.
5544
5545       • Removed the Crypto.Protocol.Chaffing module.
5546
5547       • Removed   the   parameters   disabled_shortcut   and   overflow  from
5548         Crypto.Util.Counter.new.
5549
5550   Other changes
5551Crypto.Random stops being a userspace CSPRNG. It is now a pure  wrap‐
5552         per over os.urandom.
5553
5554       • Added certain resistance against side-channel attacks for GHASH (GCM)
5555         and DSA.
5556
5557       • More test vectors for HMAC-RIPEMD-160.
5558
5559       • Update libtomcrypt headers  and  code  to  v1.17  (kudos  to  Richard
5560         Mitchell).
5561
5562       • RSA and DSA keys are checked for consistency as they are imported.
5563
5564       • Simplified build process by removing autoconf.
5565
5566       • Speed optimization to PBKDF2.
5567
5568       • Add support for MSVC.
5569
5570       • Replaced HMAC code with a BSD implementation. Clarified that starting
5571         from the fork, all contributions are released under the BSD license.
5572

LICENSE

5574       The source code in PyCryptodome is partially in the public  domain  and
5575       partially released under the BSD 2-Clause license.
5576
5577       In either case, there are minimal if no restrictions on the redistribu‐
5578       tion, modification and usage of the software.
5579
5580   Public domain
5581       All code originating from  PyCrypto is free and  unencumbered  software
5582       released into the public domain.
5583
5584       Anyone  is  free  to copy, modify, publish, use, compile, sell, or dis‐
5585       tribute this software, either in source code form or as a compiled  bi‐
5586       nary, for any purpose, commercial or non-commercial, and by any means.
5587
5588       In  jurisdictions  that recognize copyright laws, the author or authors
5589       of this software dedicate any and all copyright interest in  the  soft‐
5590       ware  to  the public domain. We make this dedication for the benefit of
5591       the public at large and to the detriment of our heirs  and  successors.
5592       We  intend this dedication to be an overt act of relinquishment in per‐
5593       petuity of all present and future rights to this software  under  copy‐
5594       right law.
5595
5596       THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
5597       OR IMPLIED, INCLUDING  BUT  NOT  LIMITED  TO  THE  WARRANTIES  OF  MER‐
5598       CHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN
5599       NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM,  DAMAGES  OR  OTHER
5600       LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
5601       FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR  THE  USE  OR  OTHER
5602       DEALINGS IN THE SOFTWARE.
5603
5604       For more information, please refer to <http://unlicense.org>
5605
5606   BSD license
5607       All direct contributions to PyCryptodome are released under the follow‐
5608       ing license. The copyright of each piece belongs to the respective  au‐
5609       thor.
5610
5611       Redistribution and use in source and binary forms, with or without mod‐
5612       ification, are permitted provided that  the  following  conditions  are
5613       met:
5614
5615       1. Redistributions  of  source code must retain the above copyright no‐
5616          tice, this list of conditions and the following disclaimer.
5617
5618       2. Redistributions in binary form must reproduce  the  above  copyright
5619          notice,  this list of conditions and the following disclaimer in the
5620          documentation and/or other materials provided with the distribution.
5621
5622       THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
5623       IS"  AND  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
5624       TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTIC‐
5625       ULAR  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
5626       CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,  INCIDENTAL,  SPECIAL,
5627       EXEMPLARY,  OR  CONSEQUENTIAL  DAMAGES  (INCLUDING, BUT NOT LIMITED TO,
5628       PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;  LOSS  OF  USE,  DATA,  OR
5629       PROFITS;  OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
5630       LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,  OR  TORT  (INCLUDING
5631       NEGLIGENCE  OR  OTHERWISE)  ARISING  IN  ANY WAY OUT OF THE USE OF THIS
5632       SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
5633
5634   OCB license
5635       The OCB cipher  mode  is  patented  in  the  US  under  patent  numbers
5636       7,949,129  and 8,321,675. The directory Doc/ocb contains three free li‐
5637       censes for implementors and users. As a general statement, OCB  can  be
5638       freely  used for software not meant for military purposes. Contact your
5639       attorney for further information.
5640

AUTHOR

5642       Legrandin
5643
5645       2021, Helder Eijs
5646
5647
5648
5649
56503.10                             Mar 31, 2021                  PYCRYPTODOME(1)
Impressum