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
17          install it with:
18
19             pip install pycryptodome
20
21          In this case, all modules are installed under the Crypto package.
22
23          One must avoid having both PyCrypto and  PyCryptodome  installed  at
24          the same time, as they will interfere with each other.
25
26          This option is therefore recommended only when you are sure that the
27          whole application is deployed in a virtualenv.
28
29       2. a library independent of the old PyCrypto.  You install it with:
30
31             pip install pycryptodomex
32
33          In this case, all modules are installed under the  Cryptodome  pack‐
34          age.  PyCrypto and PyCryptodome can coexist.
35
36       For  faster  public  key  operations in Unix, you should install GMP in
37       your system.
38
39       PyCryptodome is a fork of PyCrypto. It brings  the  following  enhance‐
40       ments with respect to the last official version of PyCrypto (2.6.1):
41
42       · Authenticated encryption modes (GCM, CCM, EAX, SIV, OCB)
43
44       · Accelerated AES on Intel platforms via AES-NI
45
46       · First class support for PyPy
47
48       · Elliptic  curves  cryptography  (NIST  P-256,  P-384 and P-521 curves
49         only)
50
51       · Better and more compact API (nonce and  iv  attributes  for  ciphers,
52         automatic  generation of random nonces and IVs, simplified CTR cipher
53         mode, and more)
54
55       · SHA-3 (including SHAKE XOFs), truncated SHA-512 and BLAKE2 hash algo‐
56         rithms
57
58       · Salsa20 and ChaCha20/XChaCha20 stream ciphers
59
60       · Poly1305 MAC
61
62       · ChaCha20-Poly1305 and XChaCha20-Poly1305 authenticated ciphers
63
64       · scrypt, bcrypt and HKDF derivation functions
65
66       · Deterministic (EC)DSA
67
68       · Password-protected PKCS#8 key containers
69
70       · Shamir's Secret Sharing scheme
71
72       · Random  numbers  get  sourced  directly  from  the OS (and not from a
73         CSPRNG in userspace)
74
75       · Simplified install process, including better support for Windows
76
77       · Cleaner RSA and DSA key generation (largely based on FIPS 186-4)
78
79       · Major clean ups and simplification of the code base
80
81       PyCryptodome is not a wrapper to a separate C library like OpenSSL.  To
82       the largest possible extent, algorithms are implemented in pure Python.
83       Only the pieces that are extremely critical to performance (e.g.  block
84       ciphers) are implemented as C extensions.
85
86       For more information, see the homepage.
87
88       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
96       security 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 set‐
271       up the environment for compiling the C extensions for each OS, and  how
272       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
277          pycryptodomex 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
303          pycryptodomex 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
329          pycryptodomex 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
378          pycryptodomex 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
427          pycryptodomex 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
522         · sign()
523
524         · verify()
525
526         · encrypt()
527
528         · decrypt()
529
530         · blind()
531
532         · unblind()
533
534         Applications should be updated to use instead:
535
536         · Crypto.Cipher.PKCS1_OAEP for encrypting using RSA.
537
538         · Crypto.Signature.pkcs1_15 or Crypto.Signature.pss for signing using
539           RSA.
540
541         · Crypto.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
565         expression  like  AES.new(key)  will  now fail. If ECB is the desired
566         mode, one has to explicitly use AES.new(key, AES.MODE_ECB).
567
568       · Crypto.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
580         Crypto.Cipher.Blowfish must be at least  40  bits  long  (still  very
581         weak).
582
583       The following packages, modules and functions have been removed:
584
585          · Crypto.Random.OSRNG, Crypto.Util.winrandom and Crypto.Random.rand‐
586            pool.  You should use Crypto.Random only.
587
588          · Crypto.Cipher.XOR.  If  you   just   want   to   XOR   data,   use
589            Crypto.Util.strxor.
590
591          · Crypto.Hash.new. Use Crypto.Hash.<algorithm>.new() instead.
592
593          · Crypto.Protocol.AllOrNothing
594
595          · Crypto.Protocol.Chaffing
596
597          · Crypto.Util.number.getRandomNumber
598
599          · Crypto.pct_warnings
600
601       Others:
602
603       · Support for any Python version older than 2.6 is dropped.
604

API DOCUMENTATION

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

EXAMPLES

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

FREQUENTLY ASKED QUESTIONS

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

CONTRIBUTE AND SUPPORT

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

FUTURE PLANS

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

CHANGELOG

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

LICENSE

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

AUTHOR

5646       Legrandin
5647
5649       2021, Helder Eijs
5650
5651
5652
5653
56543.10                             Feb 09, 2021                  PYCRYPTODOME(1)
Impressum