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.6 and 2.7, Python 3.4 and newer, and PyPy.
12
13       The installation procedure depends on the package you want the  library
14       to be in.  PyCryptodome can be used as:
15
16       1. an  almost  drop-in  replacement  for the old PyCrypto library.  You
17          install it with:
18
19             pip install pycryptodome
20
21          In this case, all modules are installed under the Crypto package.
22
23          One must avoid having both PyCrypto and  PyCryptodome  installed  at
24          the same time, as they will interfere with each other.
25
26          This option is therefore recommended only when you are sure that the
27          whole application is deployed in a virtualenv.
28
29       2. a library independent of the old PyCrypto.  You install it with:
30
31             pip install pycryptodomex
32
33          In this case, all modules are installed under the  Cryptodome  pack‐
34          age.  PyCrypto and PyCryptodome can coexist.
35
36       For  faster  public  key  operations in Unix, you should install GMP in
37       your system.
38
39       PyCryptodome is a fork of PyCrypto. It brings  the  following  enhance‐
40       ments with respect to the last official version of PyCrypto (2.6.1):
41
42       · Authenticated encryption modes (GCM, CCM, EAX, SIV, OCB)
43
44       · Accelerated AES on Intel platforms via AES-NI
45
46       · First class support for PyPy
47
48       · Elliptic  curves  cryptography  (NIST  P-256,  P-384 and P-521 curves
49         only)
50
51       · Better and more compact API (nonce and  iv  attributes  for  ciphers,
52         automatic  generation of random nonces and IVs, simplified CTR cipher
53         mode, and more)
54
55       · SHA-3 (including SHAKE XOFs), truncated SHA-512 and BLAKE2 hash algo‐
56         rithms
57
58       · Salsa20 and ChaCha20 stream ciphers
59
60       · Poly1305 MAC
61
62       · ChaCha20-Poly1305 authenticated cipher
63
64       · scrypt and HKDF
65
66       · Deterministic (EC)DSA
67
68       · Password-protected PKCS#8 key containers
69
70       · Shamir's Secret Sharing scheme
71
72       · Random  numbers  get  sourced  directly  from  the OS (and not from a
73         CSPRNG in userspace)
74
75       · Simplified install process, including better support for Windows
76
77       · Cleaner RSA and DSA key generation (largely based on FIPS 186-4)
78
79       · Major clean ups and simplification of the code base
80
81       PyCryptodome is not a wrapper to a separate C library like OpenSSL.  To
82       the largest possible extent, algorithms are implemented in pure Python.
83       Only the pieces that are extremely critical to performance (e.g.  block
84       ciphers) are implemented as C extensions.
85
86       For more information, see the homepage.
87
88       All the code can be downloaded from GitHub.
89

FEATURES

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

INSTALLATION

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

COMPATIBILITY WITH PYCRYPTO

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

API DOCUMENTATION

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

EXAMPLES

4266   Encrypt data with AES
4267       The following code generates a new AES128 key and encrypts a  piece  of
4268       data  into  a file.  We use the EAX mode because it allows the receiver
4269       to detect any unauthorized modification (similarly, we could have  used
4270       other authenticated encryption modes like GCM, CCM or SIV).
4271
4272          from Crypto.Cipher import AES
4273          from Crypto.Random import get_random_bytes
4274
4275          key = get_random_bytes(16)
4276          cipher = AES.new(key, AES.MODE_EAX)
4277          ciphertext, tag = cipher.encrypt_and_digest(data)
4278
4279          file_out = open("encrypted.bin", "wb")
4280          [ file_out.write(x) for x in (cipher.nonce, tag, ciphertext) ]
4281
4282       At the other end, the receiver can securely load the piece of data back
4283       (if they know the key!).  Note that the  code  generates  a  ValueError
4284       exception when tampering is detected.
4285
4286          from Crypto.Cipher import AES
4287
4288          file_in = open("encrypted.bin", "rb")
4289          nonce, tag, ciphertext = [ file_in.read(x) for x in (16, 16, -1) ]
4290
4291          # let's assume that the key is somehow available again
4292          cipher = AES.new(key, AES.MODE_EAX, nonce)
4293          data = cipher.decrypt_and_verify(ciphertext, tag)
4294
4295   Generate an RSA key
4296       The  following  code generates a new RSA key pair (secret) and saves it
4297       into a file, protected by a password.  We use the scrypt key derivation
4298       function to thwart dictionary attacks.  At the end, the code prints our
4299       the RSA public key in ASCII/PEM format:
4300
4301          from Crypto.PublicKey import RSA
4302
4303          secret_code = "Unguessable"
4304          key = RSA.generate(2048)
4305          encrypted_key = key.export_key(passphrase=secret_code, pkcs=8,
4306                                        protection="scryptAndAES128-CBC")
4307
4308          file_out = open("rsa_key.bin", "wb")
4309          file_out.write(encrypted_key)
4310
4311          print(key.publickey().export_key())
4312
4313       The following code reads the private RSA key back in, and  then  prints
4314       again the public key:
4315
4316          from Crypto.PublicKey import RSA
4317
4318          secret_code = "Unguessable"
4319          encoded_key = open("rsa_key.bin", "rb").read()
4320          key = RSA.import_key(encoded_key, passphrase=secret_code)
4321
4322          print(key.publickey().export_key())
4323
4324   Generate public key and private key
4325       The following code generates public key stored in receiver.pem and pri‐
4326       vate key stored in private.pem. These files will be used in  the  exam‐
4327       ples  below.  Every time, it generates different public key and private
4328       key pair.
4329
4330          from Crypto.PublicKey import RSA
4331
4332          key = RSA.generate(2048)
4333          private_key = key.export_key()
4334          file_out = open("private.pem", "wb")
4335          file_out.write(private_key)
4336
4337          public_key = key.publickey().export_key()
4338          file_out = open("receiver.pem", "wb")
4339          file_out.write(public_key)
4340
4341   Encrypt data with RSA
4342       The following code encrypts a piece of data for a receiver we have  the
4343       RSA  public  key  of.   The  RSA  public key is stored in a file called
4344       receiver.pem.
4345
4346       Since we want to be able to encrypt an arbitrary amount of data, we use
4347       a hybrid encryption scheme.  We use RSA with PKCS#1 OAEP for asymmetric
4348       encryption of an AES session key.  The session key can then be used  to
4349       encrypt all the actual data.
4350
4351       As  in  the  first  example,  we use the EAX mode to allow detection of
4352       unauthorized modifications.
4353
4354          from Crypto.PublicKey import RSA
4355          from Crypto.Random import get_random_bytes
4356          from Crypto.Cipher import AES, PKCS1_OAEP
4357
4358          data = "I met aliens in UFO. Here is the map.".encode("utf-8")
4359          file_out = open("encrypted_data.bin", "wb")
4360
4361          recipient_key = RSA.import_key(open("receiver.pem").read())
4362          session_key = get_random_bytes(16)
4363
4364          # Encrypt the session key with the public RSA key
4365          cipher_rsa = PKCS1_OAEP.new(recipient_key)
4366          enc_session_key = cipher_rsa.encrypt(session_key)
4367
4368          # Encrypt the data with the AES session key
4369          cipher_aes = AES.new(session_key, AES.MODE_EAX)
4370          ciphertext, tag = cipher_aes.encrypt_and_digest(data)
4371          [ file_out.write(x) for x in (enc_session_key, cipher_aes.nonce, tag, ciphertext) ]
4372
4373       The receiver has the private RSA key. They will use it to  decrypt  the
4374       session key first, and with that the rest of the file:
4375
4376          from Crypto.PublicKey import RSA
4377          from Crypto.Cipher import AES, PKCS1_OAEP
4378
4379          file_in = open("encrypted_data.bin", "rb")
4380
4381          private_key = RSA.import_key(open("private.pem").read())
4382
4383          enc_session_key, nonce, tag, ciphertext = \
4384             [ file_in.read(x) for x in (private_key.size_in_bytes(), 16, 16, -1) ]
4385
4386          # Decrypt the session key with the private RSA key
4387          cipher_rsa = PKCS1_OAEP.new(private_key)
4388          session_key = cipher_rsa.decrypt(enc_session_key)
4389
4390          # Decrypt the data with the AES session key
4391          cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce)
4392          data = cipher_aes.decrypt_and_verify(ciphertext, tag)
4393          print(data.decode("utf-8"))
4394

FREQUENTLY ASKED QUESTIONS

4396   Is CTR cipher mode compatible with Java?
4397       Yes. When you instantiate your AES cipher in Java:
4398
4399          Cipher  cipher = Cipher.getInstance("AES/CTR/NoPadding");
4400
4401          SecretKeySpec keySpec = new SecretKeySpec(new byte[16], "AES");
4402          IvParameterSpec ivSpec = new IvParameterSpec(new byte[16]);
4403
4404          cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
4405
4406       You  are  effectively  using  ctr_mode without a fixed nonce and with a
4407       128-bit big endian counter starting at 0.  The counter will wrap around
4408       only after 2¹²⁸ blocks.
4409
4410       You can replicate the same keystream in PyCryptodome with:
4411
4412          ivSpec = b'\x00' * 16
4413          ctr = AES.new(keySpec, AES.MODE_CTR, initial_value=ivSpec)
4414
4415   Are RSASSA-PSS signatures compatible with Java or OpenSSL?
4416       Yes.  For Java, you must consider that by default the mask is generated
4417       by MGF1 with SHA-1 (regardless of how you hash  the  message)  and  the
4418       salt is 20 bytes long.
4419
4420       If  you  want to use another algorithm or another salt length, you must
4421       instantiate a PSSParameterSpec object, for instance:
4422
4423          Signature ss = Signature.getInstance("SHA256withRSA/PSS");
4424          AlgorithmParameters pss1 = ss.getParameters();
4425          PSSParameterSpec pssParameterSpec = new PSSParameterSpec("SHA-256", "MGF1", new MGF1ParameterSpec("SHA-256"), 32, 0xBC);
4426          ss.setParameter(spec1);
4427
4428       On the other hand, a quirk of OpenSSL (and of a  few  other  libraries,
4429       especially  if  they  are wrappers to OpenSSL) is that the default salt
4430       length is maximized, and it does not match in size the  digest  applied
4431       to  the message, as recommended in RFC8017.  In PyCryptodome, you maxi‐
4432       mize the salt length with:
4433
4434          key = RSA.import_key(open('privkey.der').read())
4435          h = SHA256.new(message)
4436          salt_bytes = key.size_in_bytes() - h.digest_size - 2
4437          signature = pss.new(key, salt_bytes=salt_bytes).sign(h)
4438
4439   Why do I get the error No module named Crypto on Windows?
4440       Check the directory where Python packages are installed, like:
4441
4442          /path/to/python/Lib/site-packages/
4443
4444       You might find a directory named  crypto,  with  all  the  PyCryptodome
4445       files in it.
4446
4447       The  most  likely  cause  is described here and you can fix the problem
4448       with:
4449
4450          pip uninstall crypto
4451          pip uninstall pycryptodome
4452          pip install pycryptodome
4453
4454       The root cause is that, in the past, you most likely have installed  an
4455       unrelated  but  similarly named package called crypto, which happens to
4456       operate under the namespace crypto.
4457
4458       The Windows filesystem is case-insensitive so  crypto  and  Crypto  are
4459       effectively  considered  the same thing.  When you subsequently install
4460       pycryptodome, pip finds that a directory named with the  target  names‐
4461       pace already exists (under the rules of the underlying filesystem), and
4462       therefore installs all the sub-packages of pycryptodome in it.  This is
4463       probably  a  reasonable behavior, if it wansn't that pip does not issue
4464       any warning even if it could detect the issue.
4465

CONTRIBUTE AND SUPPORT

4467       · Do not be afraid to contribute with small and  apparently  insignifi‐
4468         cant improvements like correction to typos. Every change counts.
4469
4470       · Read  carefully the license of PyCryptodome. By submitting your code,
4471         you acknowledge that you accept to release it according  to  the  BSD
4472         2-clause license.
4473
4474       · You  must disclaim which parts of your code in your contribution were
4475         partially copied or derived from an existing source. Ensure that  the
4476         original is licensed in a way compatible to the BSD 2-clause license.
4477
4478       · You  can  propose  changes in any way you find most convenient.  How‐
4479         ever, the preferred approach is to:
4480
4481         · Clone the main repository on GitHub.
4482
4483         · Create a branch and modify the code.
4484
4485         · Send a pull request upstream with a meaningful description.
4486
4487       · Provide tests (in Crypto.SelfTest) along with code. If you fix a  bug
4488         add  a  test  that  fails in the current version and passes with your
4489         change.
4490
4491       · If your  change  breaks  backward  compatibility,  highlight  it  and
4492         include a justification.
4493
4494       · Ensure that your code complies to PEP8 and PEP257.
4495
4496       · If  you add or modify a public interface, make sure the relevant type
4497         stubs remain up to date.
4498
4499       · Ensure that your code does not use constructs or includes modules not
4500         present in Python 2.6.
4501
4502       · Add a short summary of the change to the file Changelog.rst.
4503
4504       · Add your name to the list of contributors in the file AUTHORS.rst.
4505
4506       The PyCryptodome mailing list is hosted on Google Groups.  You can mail
4507       any comment or question to pycryptodome@googlegroups.com.
4508
4509       Bug reports can be filed on the GitHub tracker.
4510

FUTURE PLANS

4512       Future releases will include:
4513
4514       · Update Crypto.Signature.DSS to FIPS 186-4
4515
4516       · Make all hash objects non-copiable  and  immutable  after  the  first
4517         digest
4518
4519       · Add alias 'segment_bits' to parameter 'segment_size' for CFB
4520
4521       · Coverage testing
4522
4523       · Implement AES with bitslicing
4524
4525       · Add unit tests for PEM I/O
4526
4527       · Move old ciphers into a Museum submodule
4528
4529       · Add more ECC curves
4530
4531       · Import/export of ECC keys with compressed points
4532
4533       ·
4534
4535         Add algorithms:
4536
4537                · Elliptic Curves (ECIES, ECDH)
4538
4539                · Camellia, GOST
4540
4541                · Diffie-Hellman
4542
4543                · bcrypt
4544
4545                · argon2
4546
4547                · SRP
4548
4549       ·
4550
4551         Add more key management:
4552
4553                · Export/import of DSA domain parameters
4554
4555                · JWK
4556
4557       · Add support for CMS/PKCS#7
4558
4559       · Add support for RNG backed by PKCS#11 and/or KMIP
4560
4561       · Add support for Format-Preserving Encryption
4562
4563       · Remove dependency on libtomcrypto headers
4564
4565       · Speed up (T)DES with a bitsliced implementation
4566
4567       · Run lint on the C code
4568
4569       · Add (minimal) support for PGP
4570
4571       · Add (minimal) support for PKIX / X.509
4572

CHANGELOG

4574   3.8.1 (4 April 2019)
4575   New features
4576       · Add   support  for  loading  PEM  files  encrypted  with  AES192-CBC,
4577         AES256-CBC, and AES256-GCM.
4578
4579       · When importing ECC keys, ignore EC PARAMS section that  was  included
4580         by some openssl commands.
4581
4582   Resolved issues
4583       · repr() did not work for ECC.EccKey.
4584
4585       · Fix installation in development mode.
4586
4587       · Minimal length for Blowfish cipher is 32 bits, not 40 bits.
4588
4589       · Various updates to docs.
4590
4591   3.8.0 (23 March 2019)
4592   New features
4593       · Speed-up  ECC performance. ECDSA is 33 times faster on the NIST P-256
4594         curve.
4595
4596       · Added support for NIST P-384 and P-521 curves.
4597
4598       · EccKey has new methods size_in_bits() and size_in_bytes().
4599
4600       · Support HMAC-SHA224, HMAC-SHA256,  HMAC-SHA384,  and  HMAC-SHA512  in
4601         PBE2/PBKDF2.
4602
4603   Resolved issues
4604       · DER  objects  were  not  rejected if their length field had a leading
4605         zero.
4606
4607       · Allow legacy RC2 ciphers to have 40-bit keys.
4608
4609       · ASN.1 Object IDs did not allow the value 0 in the path.
4610
4611   Breaks in compatibility
4612       · point_at_infinity()  becomes  an  instance  method  for   Crypto.Pub‐
4613         licKey.ECC.EccKey, from a static one.
4614
4615   3.7.3 (19 January 2019)
4616   Resolved issues
4617       · GH#258:  False  positive  on  PSS signatures when externally provided
4618         salt is too long.
4619
4620       · Include type stub files for Crypto.IO and Crypto.Util.
4621
4622   3.7.2 (26 November 2018)
4623   Resolved issues
4624       · GH#242: Fixed compilation problem on ARM platforms.
4625
4626   3.7.1 (25 November 2018)
4627   New features
4628       · Added type stubs to enable static type checking with mypy. Thanks  to
4629         Michael Nix.
4630
4631       · New update_after_digest flag for CMAC.
4632
4633   Resolved issues
4634       · GH#232: Fixed problem with gcc 4.x when compiling ghash_clmul.c.
4635
4636       · GH#238:  Incorrect  digest  value  produced by CMAC after cloning the
4637         object.
4638
4639       · Method update() of an EAX cipher object was returning the  underlying
4640         CMAC object, instead of the EAX object itself.
4641
4642       · Method  update() of a CMAC object was not throwing an exception after
4643         the digest was computed (with digest() or verify()).
4644
4645   3.7.0 (27 October 2018)
4646   New features
4647       · Added support for Poly1305 MAC (with AES and ChaCha20 ciphers for key
4648         derivation).
4649
4650       · Added support for ChaCha20-Poly1305 AEAD cipher.
4651
4652       · New      parameter      output     for     Crypto.Util.strxor.strxor,
4653         Crypto.Util.strxor.strxor_c, encrypt and decrypt methods in symmetric
4654         ciphers (Crypto.Cipher package).  output is a pre-allocated buffer (a
4655         bytearray or a writeable memoryview) where the result must be stored.
4656         This  requires  less  memory for very large payloads; it is also more
4657         efficient when encrypting (or decrypting) several small payloads.
4658
4659   Resolved issues
4660       · GH#266: AES-GCM hangs when processing more than 4GB at a time on  x86
4661         with PCLMULQDQ instruction.
4662
4663   Breaks in compatibility
4664       · Drop support for Python 3.3.
4665
4666       · Remove    Crypto.Util.py3compat.unhexlify   and   Crypto.Util.py3com‐
4667         pat.hexlify.
4668
4669       · With the old Python 2.6, use only ctypes (and not cffi) to  interface
4670         to native code.
4671
4672   3.6.6 (17 August 2018)
4673   Resolved issues
4674       · GH#198:  Fix vulnerability on AESNI ECB with payloads smaller than 16
4675         bytes (CVE-2018-15560).
4676
4677   3.6.5 (12 August 2018)
4678   Resolved issues
4679       · GH#187: Fixed incorrect AES encryption/decryption with AES  accelera‐
4680         tion on x86 due to gcc's optimization and strict aliasing rules.
4681
4682       · GH#188:  More  prime number candidates than necessary where discarded
4683         as composite due to the limited way D values  were  searched  in  the
4684         Lucas test.
4685
4686       · Fixed ResouceWarnings and DeprecationWarnings.
4687
4688       · Workaround     for     Python     3.7.0    bug    on    Windows    (‐
4689         https://bugs.python.org/issue34108).
4690
4691   3.6.4 (10 July 2018)
4692   New features
4693       · Build Python 3.7 wheels on Linux, Windows and Mac.
4694
4695   Resolved issues
4696       · GH#178: Rename _cpuid module to make upgrades more robust.
4697
4698       · More  meaningful  exceptions  in  case  of  mismatch  in  IV   length
4699         (CBC/OFB/CFB modes).
4700
4701       · Fix compilation issues on Solaris 10/11.
4702
4703   3.6.3 (21 June 2018)
4704   Resolved issues
4705       · GH#175:  Fixed  incorrect  results for CTR encryption/decryption with
4706         more than 8 blocks.
4707
4708   3.6.2 (19 June 2018)
4709   New features
4710       · ChaCha20 accepts 96 bit nonces (in addition  to  64  bit  nonces)  as
4711         defined in RFC7539.
4712
4713       · Accelerate AES-GCM on x86 using PCLMULQDQ instruction.
4714
4715       · Accelerate  AES-ECB  and  AES-CTR on x86 by pipelining AESNI instruc‐
4716         tions.
4717
4718       · As result of the two improvements above, on x86 (Broadwell):
4719
4720         · AES-ECB and AES-CTR are 3x faster
4721
4722         · AES-GCM is 9x faster
4723
4724   Resolved issues
4725       · On Windows, MPIR library was stilled pulled in if renamed to gmp.dll.
4726
4727   Breaks in compatibility
4728       · In Crypto.Util.number, functions floor_div and  exact_div  have  been
4729         removed. Also, ceil_div is limited to non-negative terms only.
4730
4731   3.6.1 (15 April 2018)
4732   New features
4733       · Added  Google Wycheproof tests (https://github.com/google/wycheproof)
4734         for RSA, DSA, ECDSA, GCM, SIV, EAX, CMAC.
4735
4736       · New parameter mac_len (length of MAC tag) for CMAC.
4737
4738   Resolved issues
4739       · In certain circumstances (at counter wrapping, which happens on aver‐
4740         age after 32 GB) AES GCM produced wrong ciphertexts.
4741
4742       · Method  encrypt()  of  AES  SIV cipher could be still called, whereas
4743         only encrypt_and_digest() is allowed.
4744
4745   3.6.0 (8 April 2018)
4746   New features
4747       · Introduced export_key and deprecated exportKey for DSA  and  RSA  key
4748         objects.
4749
4750       · Ciphers and hash functions accept memoryview objects in input.
4751
4752       · Added support for SHA-512/224 and SHA-512/256.
4753
4754   Resolved issues
4755       · Reintroduced Crypto.__version__ variable as in PyCrypto.
4756
4757       · Fixed compilation problem with MinGW.
4758
4759   3.5.1 (8 March 2018)
4760   Resolved issues
4761       · GH#142. Fix mismatch with declaration and definition of addmul128.
4762
4763   3.5.0 (7 March 2018)
4764   New features
4765       · Import and export of ECC curves in compressed form.
4766
4767       · The initial counter for a cipher in CTR mode can be a byte string (in
4768         addition to an integer).
4769
4770       · Faster PBKDF2 for HMAC-based PRFs (at least 20x for short  passwords,
4771         more  for  longer passwords). Thanks to Christian Heimes for pointing
4772         out the implementation was under-optimized.
4773
4774       · The salt for PBKDF2 can be either a string or bytes (GH#67).
4775
4776       · Ciphers and hash functions accept data as bytearray, not just  binary
4777         strings.
4778
4779       · The old SHA-1 and MD5 hash functions are available even when Python's
4780         own hashlib does not include them.
4781
4782   Resolved issues
4783       · Without libgmp, modular  exponentiation  (since  v3.4.8)  crashed  on
4784         32-bit big-endian systems.
4785
4786   Breaks in compatibility
4787       · Removed support for Python < 2.6.
4788
4789   3.4.12 (5 February 2018)
4790   Resolved issues
4791       · GH#129. pycryptodomex could only be installed via wheels.
4792
4793   3.4.11 (5 February 2018)
4794   Resolved issues
4795       · GH#121.  the  record  list  was  still not correct due to PEP3147 and
4796         __pycache__ directories. Thanks again to John O'Brien.
4797
4798   3.4.10 (2 February 2018)
4799   Resolved issues
4800       · When creating ElGamal keys, the generator wasn't  a  square  residue:
4801         ElGamal  encryption  done  with those keys cannot be secure under the
4802         DDH assumption. Thanks to Weikeng Chen.
4803
4804   3.4.9 (1 February 2018)
4805   New features
4806       · More meaningful error messages while importing an ECC key.
4807
4808   Resolved issues
4809       · GH#123 and #125. The SSE2 command line switch was not  always  passed
4810         on 32-bit x86 platforms.
4811
4812       · GH#121.  The  record  list (--record) was not always correctly filled
4813         for the pycryptodomex package. Thanks to John W. O'Brien.
4814
4815   3.4.8 (27 January 2018)
4816   New features
4817       · Added a native extension in pure C for modular exponentiation,  opti‐
4818         mized for SSE2 on x86.  In the process, we drop support for the arbi‐
4819         trary arithmetic library MPIR on Windows, which is painful to compile
4820         and deploy.  The custom  modular exponentiation is 130% (160%) slower
4821         on an Intel CPU in 32-bit (64-bit) mode,  compared  to  MPIR.  Still,
4822         that  is  much faster that CPython's own pow() function which is 900%
4823         (855%) slower than MPIR. Support for the GMP library on Unix remains.
4824
4825       · Added support for manylinux wheels.
4826
4827       · Support for Python 3.7.
4828
4829   Resolved issues
4830       · The DSA parameter 'p' prime was created with 255  bits  cleared  (but
4831         still with the correct strength).
4832
4833       · GH#106.  Not  all  docs  were  included  in  the tar ball.  Thanks to
4834         Christopher Hoskin.
4835
4836       · GH#109. ECDSA verification failed for DER encoded signatures.  Thanks
4837         to Alastair Houghton.
4838
4839       · Human-friendly messages for padding errors with ECB and CBC.
4840
4841   3.4.7 (26 August 2017)
4842   New features
4843       · API documentation is made with sphinx instead of epydoc.
4844
4845       · Start using importlib instead of imp where available.
4846
4847   Resolved issues
4848       · GH#82. Fixed PEM header for RSA/DSA public keys.
4849
4850   3.4.6 (18 May 2017)
4851   Resolved issues
4852       · GH#65.  Keccak,  SHA3,  SHAKE and the seek functionality for ChaCha20
4853         were not working on  big  endian  machines.  Fixed.  Thanks  to  Mike
4854         Gilbert.
4855
4856       · A few fixes in the documentation.
4857
4858   3.4.5 (6 February 2017)
4859   Resolved issues
4860       · The library can also be compiled using MinGW.
4861
4862   3.4.4 (1 February 2017)
4863   Resolved issues
4864       · Removed use of alloca().
4865
4866       · [Security] Removed implementation of deprecated "quick check" feature
4867         of PGP block cipher mode.
4868
4869       · Improved the performance of scrypt by converting some Python to C.
4870
4871   3.4.3 (17 October 2016)
4872   Resolved issues
4873       · Undefined warning was raised with libgmp version < 5
4874
4875       · Forgot inclusion of alloca.h
4876
4877       · Fixed a warning about type mismatch raised by recent versions of cffi
4878
4879   3.4.2 (8 March 2016)
4880   Resolved issues
4881       · Fix renaming of package for install command.
4882
4883   3.4.1 (21 February 2016)
4884   New features
4885       · Added option to install the  library  under  the  Cryptodome  package
4886         (instead of Crypto).
4887
4888   3.4 (7 February 2016)
4889   New features
4890       · Added  Crypto.PublicKey.ECC module (NIST P-256 curve only), including
4891         export/import of ECC keys.
4892
4893       · Added support for ECDSA (FIPS 186-3 and RFC6979).
4894
4895       · For CBC/CFB/OFB/CTR cipher objects, encrypt() and decrypt() cannot be
4896         intermixed.
4897
4898       · CBC/CFB/OFB,  the  cipher  objects  have  both  IV and iv attributes.
4899         new() accepts IV as well as iv as parameter.
4900
4901       · For CFB/OPENPGP cipher object, encrypt() and decrypt() do not require
4902         the plaintext or ciphertext pieces to have length multiple of the CFB
4903         segment size.
4904
4905       · Added dedicated tests for all cipher modes, including NIST test  vec‐
4906         tors
4907
4908       · CTR/CCM/EAX/GCM/SIV/Salsa20/ChaCha20   objects   expose   the   nonce
4909         attribute.
4910
4911       · For performance reasons, CCM cipher optionally accepted a  pre-decla‐
4912         ration of the length of the associated data, but never checked if the
4913         actual data passed to the cipher really  matched  that  length.  Such
4914         check is now enforced.
4915
4916       · CTR  cipher objects accept parameter nonce and possibly initial_value
4917         in alternative to counter (which is deprecated).
4918
4919       · All iv/IV and nonce parameters are optional. If  not  provided,  they
4920         will  be randomly generated (exception: nonce for CTR mode in case of
4921         block sizes smaller than 16 bytes).
4922
4923       · Refactored ARC2 cipher.
4924
4925       · Added Crypto.Cipher.DES3.adjust_key_parity() function.
4926
4927       · Added RSA.import_key as an  alias  to  the  deprecated  RSA.importKey
4928         (same for the DSA module).
4929
4930       · Added size_in_bits() and size_in_bytes() methods to RsaKey.
4931
4932   Resolved issues
4933       · RSA  key  size  is now returned correctly in RsaKey.__repr__() method
4934         (kudos to hannesv).
4935
4936       · CTR mode does not modify anymore counter parameter  passed  to  new()
4937         method.
4938
4939       · CTR raises OverflowError instead of ValueError when the counter wraps
4940         around.
4941
4942       · PEM files with Windows newlines could not be imported.
4943
4944       · Crypto.IO.PEM and Crypto.IO.PKCS8 used to accept empty passphrases.
4945
4946       · GH#6: NotImplementedError now raised for  unsupported  methods  sign,
4947         verify,  encrypt, decrypt, blind, unblind and size in objects RsaKey,
4948         DsaKey, ElGamalKey.
4949
4950   Breaks in compatibility
4951       · Parameter segment_size cannot be 0 for the CFB mode.
4952
4953       · For OCB ciphers, a final call without parameters to encrypt must  end
4954         a sequence of calls to encrypt with data (similarly for decrypt).
4955
4956       · Key  size  for  ARC2, ARC4 and Blowfish must be at least 40 bits long
4957         (still very weak).
4958
4959       · DES3 (Triple DES module) does not allow keys that degenerate to  Sin‐
4960         gle DES.
4961
4962       · Removed method getRandomNumber in Crypto.Util.number.
4963
4964       · Removed module Crypto.pct_warnings.
4965
4966       · Removed attribute Crypto.PublicKey.RSA.algorithmIdentifier.
4967
4968   3.3.1 (1 November 2015)
4969   New features
4970       · Opt-in for update() after digest() for SHA-3, keccak, BLAKE2 hashes
4971
4972   Resolved issues
4973       · Removed unused SHA-3 and keccak test vectors, therefore significantly
4974         reducing the package from 13MB to 3MB.
4975
4976   Breaks in compatibility
4977       · Removed method copy() from BLAKE2 hashes
4978
4979       · Removed ability to update() a BLAKE2 hash after  the  first  call  to
4980         (hex)digest()
4981
4982   3.3 (29 October 2015)
4983   New features
4984       · Windows wheels bundle the MPIR library
4985
4986       · Detection of faults occurring during secret RSA operations
4987
4988       · Detection of non-prime (weak) q value in DSA domain parameters
4989
4990       · Added  original  Keccak  hash  family (b=1600 only).  In the process,
4991         simplified the C code base for SHA-3.
4992
4993       · Added SHAKE128 and SHAKE256 (of SHA-3 family)
4994
4995   Resolved issues
4996       · GH#3: gcc 4.4.7 unhappy about double typedef
4997
4998   Breaks in compatibility
4999       · Removed method copy() from all SHA-3 hashes
5000
5001       · Removed ability to update() a SHA-3 hash  after  the  first  call  to
5002         (hex)digest()
5003
5004   3.2.1 (9 September 2015)
5005   New features
5006       · Windows wheels are automatically built on Appveyor
5007
5008   3.2 (6 September 2015)
5009   New features
5010       · Added hash functions BLAKE2b and BLAKE2s.
5011
5012       · Added stream cipher ChaCha20.
5013
5014       · Added OCB cipher mode.
5015
5016       · CMAC  raises  an exception whenever the message length is found to be
5017         too large and the chance of collisions not negligeable.
5018
5019       · New attribute oid for Hash objects with ASN.1 Object ID
5020
5021       · Added Crypto.Signature.pss and Crypto.Signature.pkcs1_15
5022
5023       · Added NIST test vectors (roughly 1200) for PKCS#1 v1.5 and PSS signa‐
5024         tures.
5025
5026   Resolved issues
5027       · tomcrypt_macros.h asm error #1
5028
5029   Breaks in compatibility
5030       · Removed  keyword  verify_x509_cert  from module method importKey (RSA
5031         and DSA).
5032
5033       · Reverted to original PyCrypto behavior of method verify in PKCS1_v1_5
5034         and PKCS1_PSS.
5035
5036   3.1 (15 March 2015)
5037   New features
5038       · Speed  up  execution of Public Key algorithms on PyPy, when backed by
5039         the Gnu Multiprecision (GMP) library.
5040
5041       · GMP headers and static libraries are not required anymore at the time
5042         PyCryptodome  is  built. Instead, the code will automatically use the
5043         GMP dynamic library (.so/.DLL) if found in the system at runtime.
5044
5045       · Reduced the amount of C code by almost 40% (4700 lines).  Modularized
5046         and  simplified  all  code  (C  and Python) related to block ciphers.
5047         Pycryptodome is now free of CPython extensions.
5048
5049       · Add support for CI in Windows via Appveyor.
5050
5051       · RSA and DSA key generation more closely follows FIPS 186-4 (though it
5052         is not 100% compliant).
5053
5054   Resolved issues
5055       · None
5056
5057   Breaks in compatibility
5058       · New dependency on ctypes with Python 2.4.
5059
5060       · The  counter  parameter  of  a  CTR mode cipher must be generated via
5061         Crypto.Util.Counter. It cannot be a generic callable anymore.
5062
5063       · Removed the Crypto.Random.Fortuna package (due to lack of  test  vec‐
5064         tors).
5065
5066       · Removed the Crypto.Hash.new function.
5067
5068       · The allow_wraparound parameter of Crypto.Util.Counter is ignored.  An
5069         exception is always generated if the counter is reused.
5070
5071       · DSA.generate, RSA.generate and ElGamal.generate  do  not  accept  the
5072         progress_func parameter anymore.
5073
5074       · Removed Crypto.PublicKey.RSA.RSAImplementation.
5075
5076       · Removed Crypto.PublicKey.DSA.DSAImplementation.
5077
5078       · Removed ambiguous method size() from RSA, DSA and ElGamal keys.
5079
5080   3.0 (24 June 2014)
5081   New features
5082       · Initial support for PyPy.
5083
5084       · SHA-3  hash  family  based  on the April 2014 draft of FIPS 202.  See
5085         modules Crypto.Hash.SHA3_224/256/384/512.  Initial  Keccak  patch  by
5086         Fabrizio Tarizzo.
5087
5088       · Salsa20  stream  cipher.  See module Crypto.Cipher.Salsa20.  Patch by
5089         Fabrizio Tarizzo.
5090
5091       · Colin  Percival's  scrypt  key  derivation  function   (Crypto.Proto‐
5092         col.KDF.scrypt).
5093
5094       · Proper interface to FIPS 186-3 DSA. See module Crypto.Signature.DSS.
5095
5096       · Deterministic DSA (RFC6979). Again, see Crypto.Signature.DSS.
5097
5098       · HMAC-based  Extract-and-Expand key derivation function (Crypto.Proto‐
5099         col.KDF.HKDF, RFC5869).
5100
5101       · Shamir's Secret Sharing protocol,  compatible  with  ssss  (128  bits
5102         only).  See module Crypto.Protocol.SecretSharing.
5103
5104       · Ability to generate a DSA key given the domain parameters.
5105
5106       · Ability to test installation with a simple python -m Crypto.SelfTest.
5107
5108   Resolved issues
5109       · LP#1193521: mpz_powm_sec() (and Python) crashed when modulus was odd.
5110
5111       · Benchmarks  work  again (they broke when ECB stopped working if an IV
5112         was passed. Patch by Richard Mitchell.
5113
5114       · LP#1178485: removed some  catch-all  exception  handlers.   Patch  by
5115         Richard Mitchell.
5116
5117       · LP#1209399:  Removal  of Python wrappers caused HMAC to silently pro‐
5118         duce the wrong data with SHA-2 algorithms.
5119
5120       · LP#1279231: remove dead code  that  does  nothing  in  SHA-2  hashes.
5121         Patch by Richard Mitchell.
5122
5123       · LP#1327081: AESNI code accesses memory beyond buffer end.
5124
5125       · Stricter  checks  on  ciphertext  and plaintext size for textbook RSA
5126         (kudos to sharego).
5127
5128   Breaks in compatibility
5129       · Removed support for Python < 2.4.
5130
5131       · Removed the following methods from all  3  public  key  object  types
5132         (RSA, DSA, ElGamal):
5133
5134         · sign
5135
5136         · verify
5137
5138         · encrypt
5139
5140         · decrypt
5141
5142         · blind
5143
5144         · unblind
5145
5146         Code that uses such methods is doomed anyway. It should be fixed ASAP
5147         to   use   the   algorithms   available   in   Crypto.Signature   and
5148         Crypto.Cipher.
5149
5150       · The 3 public key object types (RSA, DSA, ElGamal) are now unpickable.
5151
5152       · Symmetric  ciphers  do  not  have  a default mode anymore (used to be
5153         ECB).  An expression like AES.new(key) will now fail. If ECB  is  the
5154         desired mode, one has to explicitly use AES.new(key, AES.MODE_ECB).
5155
5156       · Unsuccessful  verification of a signature will now raise an exception
5157         [reverted in 3.2].
5158
5159       · Removed the Crypto.Random.OSRNG package.
5160
5161       · Removed the Crypto.Util.winrandom module.
5162
5163       · Removed the Crypto.Random.randpool module.
5164
5165       · Removed the Crypto.Cipher.XOR module.
5166
5167       · Removed the Crypto.Protocol.AllOrNothing module.
5168
5169       · Removed the Crypto.Protocol.Chaffing module.
5170
5171       · Removed  the   parameters   disabled_shortcut   and   overflow   from
5172         Crypto.Util.Counter.new.
5173
5174   Other changes
5175       · Crypto.Random  stops being a userspace CSPRNG. It is now a pure wrap‐
5176         per over os.urandom.
5177
5178       · Added certain resistance against side-channel attacks for GHASH (GCM)
5179         and DSA.
5180
5181       · More test vectors for HMAC-RIPEMD-160.
5182
5183       · Update  libtomcrypt  headers  and  code  to  v1.17  (kudos to Richard
5184         Mitchell).
5185
5186       · RSA and DSA keys are checked for consistency as they are imported.
5187
5188       · Simplified build process by removing autoconf.
5189
5190       · Speed optimization to PBKDF2.
5191
5192       · Add support for MSVC.
5193
5194       · Replaced HMAC code with a BSD implementation. Clarified that starting
5195         from the fork, all contributions are released under the BSD license.
5196

LICENSE

5198       The  source  code in PyCryptodome is partially in the public domain and
5199       partially released under the BSD 2-Clause license.
5200
5201       In either case, there are minimal if no restrictions on the redistribu‐
5202       tion, modification and usage of the software.
5203
5204   Public domain
5205       All  code  originating from  PyCrypto is free and unencumbered software
5206       released into the public domain.
5207
5208       Anyone is free to copy, modify, publish, use, compile,  sell,  or  dis‐
5209       tribute  this  software,  either  in  source code form or as a compiled
5210       binary, for any purpose,  commercial  or  non-commercial,  and  by  any
5211       means.
5212
5213       In  jurisdictions  that recognize copyright laws, the author or authors
5214       of this software dedicate any and all copyright interest in  the  soft‐
5215       ware  to  the public domain. We make this dedication for the benefit of
5216       the public at large and to the detriment of our heirs  and  successors.
5217       We  intend this dedication to be an overt act of relinquishment in per‐
5218       petuity of all present and future rights to this software  under  copy‐
5219       right law.
5220
5221       THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
5222       OR IMPLIED, INCLUDING  BUT  NOT  LIMITED  TO  THE  WARRANTIES  OF  MER‐
5223       CHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN
5224       NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM,  DAMAGES  OR  OTHER
5225       LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
5226       FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR  THE  USE  OR  OTHER
5227       DEALINGS IN THE SOFTWARE.
5228
5229       For more information, please refer to <http://unlicense.org>
5230
5231   BSD license
5232       All direct contributions to PyCryptodome are released under the follow‐
5233       ing license. The copyright of each  piece  belongs  to  the  respective
5234       author.
5235
5236       Redistribution and use in source and binary forms, with or without mod‐
5237       ification, are permitted provided that  the  following  conditions  are
5238       met:
5239
5240       1. Redistributions  of  source  code  must  retain  the above copyright
5241          notice, this list of conditions and the following disclaimer.
5242
5243       2. Redistributions in binary form must reproduce  the  above  copyright
5244          notice,  this list of conditions and the following disclaimer in the
5245          documentation and/or other materials provided with the distribution.
5246
5247       THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
5248       IS"  AND  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
5249       TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTIC‐
5250       ULAR  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
5251       CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,  INCIDENTAL,  SPECIAL,
5252       EXEMPLARY,  OR  CONSEQUENTIAL  DAMAGES  (INCLUDING, BUT NOT LIMITED TO,
5253       PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;  LOSS  OF  USE,  DATA,  OR
5254       PROFITS;  OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
5255       LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,  OR  TORT  (INCLUDING
5256       NEGLIGENCE  OR  OTHERWISE)  ARISING  IN  ANY WAY OUT OF THE USE OF THIS
5257       SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
5258
5259   OCB license
5260       The OCB cipher  mode  is  patented  in  the  US  under  patent  numbers
5261       7,949,129  and  8,321,675.  The  directory  Doc/ocb contains three free
5262       licenses for implementors and users. As a general statement, OCB can be
5263       freely  used for software not meant for military purposes. Contact your
5264       attorney for further information.
5265
5266   Apache 2.0 license (Wycheproof)
5267                     Apache License
5268
5269                 Version 2.0, January 2004
5270
5271              http://www.apache.org/licenses/
5272
5273          TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
5274
5275          1. Definitions.
5276
5277             "License" shall mean the terms and conditions for use,  reproduc‐
5278             tion, and distribution as defined by Sections 1 through 9 of this
5279             document.
5280
5281             "Licensor" shall mean the copyright owner or entity authorized by
5282             the copyright owner that is granting the License.
5283
5284             "Legal  Entity" shall mean the union of the acting entity and all
5285             other entities that control, are controlled by, or are under com‐
5286             mon  control  with  that entity. For the purposes of this defini‐
5287             tion, "control" means (i) the power, direct or indirect, to cause
5288             the  direction  or management of such entity, whether by contract
5289             or otherwise, or (ii) ownership of fifty percent (50%) or more of
5290             the  outstanding  shares,  or  (iii) beneficial ownership of such
5291             entity.
5292
5293             "You" (or "Your") shall mean an individual or Legal Entity  exer‐
5294             cising permissions granted by this License.
5295
5296             "Source"  form shall mean the preferred form for making modifica‐
5297             tions, including but not limited to software source  code,  docu‐
5298             mentation source, and configuration files.
5299
5300             "Object"  form  shall  mean  any  form  resulting from mechanical
5301             transformation or translation of a Source form, including but not
5302             limited  to  compiled  object  code, generated documentation, and
5303             conversions to other media types.
5304
5305             "Work" shall mean the work of authorship, whether  in  Source  or
5306             Object  form, made available under the License, as indicated by a
5307             copyright notice that is included in or attached to the work  (an
5308             example is provided in the Appendix below).
5309
5310             "Derivative  Works"  shall  mean  any  work, whether in Source or
5311             Object form, that is based on (or derived from) the Work and  for
5312             which  the  editorial  revisions,  annotations,  elaborations, or
5313             other modifications represent, as a whole, an  original  work  of
5314             authorship.  For  the  purposes of this License, Derivative Works
5315             shall not include works that remain  separable  from,  or  merely
5316             link (or bind by name) to the interfaces of, the Work and Deriva‐
5317             tive Works thereof.
5318
5319             "Contribution" shall mean any work of authorship,  including  the
5320             original  version  of the Work and any modifications or additions
5321             to that Work or Derivative Works thereof, that  is  intentionally
5322             submitted  to Licensor for inclusion in the Work by the copyright
5323             owner or by an individual or Legal Entity authorized to submit on
5324             behalf  of  the copyright owner. For the purposes of this defini‐
5325             tion, "submitted" means any form of electronic, verbal, or  writ‐
5326             ten  communication  sent  to the Licensor or its representatives,
5327             including but not limited to communication on electronic  mailing
5328             lists,  source  code  control systems, and issue tracking systems
5329             that are managed by, or on behalf of, the Licensor for  the  pur‐
5330             pose of discussing and improving the Work, but excluding communi‐
5331             cation that is conspicuously marked or  otherwise  designated  in
5332             writing by the copyright owner as "Not a Contribution."
5333
5334             "Contributor"  shall  mean  Licensor  and any individual or Legal
5335             Entity on behalf of whom a  Contribution  has  been  received  by
5336             Licensor and subsequently incorporated within the Work.
5337
5338          2. Grant  of  Copyright License. Subject to the terms and conditions
5339             of this License, each Contributor hereby grants to You a  perpet‐
5340             ual, worldwide, non-exclusive, no-charge, royalty-free, irrevoca‐
5341             ble copyright license to reproduce, prepare Derivative Works  of,
5342             publicly  display,  publicly  perform, sublicense, and distribute
5343             the Work and such Derivative Works in Source or Object form.
5344
5345          3. Grant of Patent License. Subject to the terms and  conditions  of
5346             this  License, each Contributor hereby grants to You a perpetual,
5347             worldwide, non-exclusive,  no-charge,  royalty-free,  irrevocable
5348             (except  as  stated in this section) patent license to make, have
5349             made, use, offer to sell, sell, import,  and  otherwise  transfer
5350             the  Work, where such license applies only to those patent claims
5351             licensable by such Contributor that are necessarily infringed  by
5352             their  Contribution(s) alone or by combination of their Contribu‐
5353             tion(s) with the Work to which such Contribution(s)  was  submit‐
5354             ted.  If  You  institute  patent  litigation  against  any entity
5355             (including a cross-claim or counterclaim in a  lawsuit)  alleging
5356             that the Work or a Contribution incorporated within the Work con‐
5357             stitutes direct or contributory  patent  infringement,  then  any
5358             patent  licenses  granted to You under this License for that Work
5359             shall terminate as of the date such litigation is filed.
5360
5361          4. Redistribution. You may reproduce and distribute  copies  of  the
5362             Work  or  Derivative Works thereof in any medium, with or without
5363             modifications, and in Source or Object form,  provided  that  You
5364             meet the following conditions:
5365
5366             a. You  must  give any other recipients of the Work or Derivative
5367                Works a copy of this License; and
5368
5369             b. You must cause any modified files to carry  prominent  notices
5370                stating that You changed the files; and
5371
5372             c. You  must  retain,  in the Source form of any Derivative Works
5373                that You distribute, all  copyright,  patent,  trademark,  and
5374                attribution  notices from the Source form of the Work, exclud‐
5375                ing those notices that do not pertain to any part of  the  De‐
5376                rivative Works; and
5377
5378             d. If  the Work includes a "NOTICE" text file as part of its dis‐
5379                tribution, then any Derivative Works that You distribute  must
5380                include  a  readable copy of the attribution notices contained
5381                within such NOTICE file, excluding those notices that  do  not
5382                pertain  to  any part of the Derivative Works, in at least one
5383                of the following places: within a NOTICE text file distributed
5384                as  part  of  the  Derivative Works; within the Source form or
5385                documentation, if provided along with  the  Derivative  Works;
5386                or, within a display generated by the Derivative Works, if and
5387                wherever such third-party notices normally  appear.  The  con‐
5388                tents  of  the NOTICE file are for informational purposes only
5389                and do not modify the License. You may add Your  own  attribu‐
5390                tion  notices  within  Derivative  Works  that You distribute,
5391                alongside or as an addendum to the NOTICE text from the  Work,
5392                provided  that  such  additional attribution notices cannot be
5393                construed as modifying the License.
5394
5395             You may add Your own copyright statement  to  Your  modifications
5396             and  may provide additional or different license terms and condi‐
5397             tions for use, reproduction, or distribution  of  Your  modifica‐
5398             tions, or for any such Derivative Works as a whole, provided Your
5399             use, reproduction, and distribution of the  Work  otherwise  com‐
5400             plies with the conditions stated in this License.
5401
5402          5. Submission  of  Contributions. Unless You explicitly state other‐
5403             wise, any Contribution intentionally submitted for  inclusion  in
5404             the Work by You to the Licensor shall be under the terms and con‐
5405             ditions of this License, without any additional terms  or  condi‐
5406             tions.  Notwithstanding the above, nothing herein shall supersede
5407             or modify the terms of any separate  license  agreement  you  may
5408             have executed with Licensor regarding such Contributions.
5409
5410          6. Trademarks.  This  License  does  not grant permission to use the
5411             trade names, trademarks, service marks, or product names  of  the
5412             Licensor,  except as required for reasonable and customary use in
5413             describing the origin of the Work and reproducing the content  of
5414             the NOTICE file.
5415
5416          7. Disclaimer  of  Warranty.  Unless  required  by applicable law or
5417             agreed to in writing, Licensor provides the Work (and  each  Con‐
5418             tributor provides its Contributions) on an "AS IS" BASIS, WITHOUT
5419             WARRANTIES OR CONDITIONS OF ANY KIND, either express or  implied,
5420             including,  without  limitation,  any warranties or conditions of
5421             TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR  A  PAR‐
5422             TICULAR  PURPOSE.  You are solely responsible for determining the
5423             appropriateness of using or redistributing the  Work  and  assume
5424             any risks associated with Your exercise of permissions under this
5425             License.
5426
5427          8. Limitation of Liability. In no event and under no  legal  theory,
5428             whether  in  tort (including negligence), contract, or otherwise,
5429             unless required by applicable law (such as deliberate and grossly
5430             negligent acts) or agreed to in writing, shall any Contributor be
5431             liable to You for damages, including any direct,  indirect,  spe‐
5432             cial, incidental, or consequential damages of any character aris‐
5433             ing as a result of this License or out of the use or inability to
5434             use  the  Work  (including but not limited to damages for loss of
5435             goodwill, work stoppage, computer failure or malfunction, or  any
5436             and  all  other  commercial damages or losses), even if such Con‐
5437             tributor has been advised of the possibility of such damages.
5438
5439          9. Accepting Warranty or Additional Liability. While  redistributing
5440             the  Work  or  Derivative Works thereof, You may choose to offer,
5441             and charge a fee for, acceptance of support, warranty, indemnity,
5442             or other liability obligations and/or rights consistent with this
5443             License. However, in accepting such obligations, You may act only
5444             on Your own behalf and on Your sole responsibility, not on behalf
5445             of any other Contributor, and only if  You  agree  to  indemnify,
5446             defend,  and  hold  each  Contributor  harmless for any liability
5447             incurred by, or claims asserted against, such Contributor by rea‐
5448             son of your accepting any such warranty or additional liability.
5449
5450          END OF TERMS AND CONDITIONS
5451
5452          APPENDIX: How to apply the Apache License to your work.
5453              To  apply  the Apache License to your work, attach the following
5454              boilerplate notice, with the fields enclosed  by  brackets  "[]"
5455              replaced  with  your own identifying information. (Don't include
5456              the brackets!)  The text should be enclosed in  the  appropriate
5457              comment  syntax  for  the  file format. We also recommend that a
5458              file or class name and description of purpose be included on the
5459              same "printed page" as the copyright notice for easier identifi‐
5460              cation within third-party archives.
5461
5462          Copyright [yyyy] [name of copyright owner]
5463
5464          Licensed under the Apache License, Version 2.0 (the "License");  you
5465          may  not  use  this file except in compliance with the License.  You
5466          may obtain a copy of the License at
5467              http://www.apache.org/licenses/LICENSE-2.0
5468
5469          Unless required by applicable law or agreed to in writing,  software
5470          distributed  under  the  License is distributed on an "AS IS" BASIS,
5471          WITHOUT WARRANTIES OR CONDITIONS OF  ANY  KIND,  either  express  or
5472          implied.   See  the License for the specific language governing per‐
5473          missions and limitations under the License.
5474

AUTHOR

5476       Legrandin
5477
5479       2017, Helder Eijs
5480
5481
5482
5483
54843.8                              Apr 09, 2019                  PYCRYPTODOME(1)
Impressum