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
1894
1895              Parameters
1896
1897                     · rsa_components (tuple) --
1898
1899                       A tuple of integers, with at least 2 and no more than 6
1900                       items. The items come in the following order:
1901
1902                       1. RSA modulus n.
1903
1904                       2. Public exponent e.
1905
1906                       3. Private  exponent  d.   Only  required if the key is
1907                          private.
1908
1909                       4. First factor of n (p).  Optional, but the other fac‐
1910                          tor q must also be present.
1911
1912                       5. Second factor of n (q). Optional.
1913
1914                       6. CRT  coefficient  q,  that  is  p^{-1}  ext{mod  }q.
1915                          Optional.
1916
1917
1918                     · consistency_check (boolean) --  If  True,  the  library
1919                       will  verify  that  the  provided components fulfil the
1920                       main RSA properties.
1921
1922              Raises ValueError -- when the key being imported fails the  most
1923                     basic RSA validity checks.
1924
1925              Returns: An RSA key object (RsaKey).
1926
1927       Crypto.PublicKey.RSA.import_key(extern_key, passphrase=None)
1928              Import  an RSA key (public or private half), encoded in standard
1929              form.
1930
1931              Parameters
1932
1933                     · extern_key (string or byte string) --
1934
1935                       The RSA key to import.
1936
1937                       The following formats are supported for an  RSA  public
1938                       key:
1939
1940                       · X.509 certificate (binary or PEM format)
1941
1942                       · X.509  subjectPublicKeyInfo  DER  SEQUENCE (binary or
1943                         PEM encoding)
1944
1945                       · PKCS#1  RSAPublicKey  DER  SEQUENCE  (binary  or  PEM
1946                         encoding)
1947
1948                       · OpenSSH (textual public key only)
1949
1950                       The  following formats are supported for an RSA private
1951                       key:
1952
1953                       · PKCS#1 RSAPrivateKey  DER  SEQUENCE  (binary  or  PEM
1954                         encoding)
1955
1956                       · PKCS#8  PrivateKeyInfo or EncryptedPrivateKeyInfo DER
1957                         SEQUENCE (binary or PEM encoding)
1958
1959                       · OpenSSH (textual public key only)
1960
1961                       For details  about  the  PEM  encoding,  see  RFC1421/‐
1962                       RFC1423.
1963
1964                       The  private key may be encrypted by means of a certain
1965                       pass phrase either at the PEM level or  at  the  PKCS#8
1966                       level.
1967
1968
1969                     · passphrase  (string) -- In case of an encrypted private
1970                       key, this is the pass phrase from which the  decryption
1971                       key is derived.
1972
1973              Returns: An RSA key object (RsaKey).
1974
1975              Raises ValueError/IndexError/TypeError  --  When  the  given key
1976                     cannot be parsed (possibly because  the  pass  phrase  is
1977                     wrong).
1978
1979       class Crypto.PublicKey.RSA.RsaKey(**kwargs)
1980              Class  defining an actual RSA key.  Do not instantiate directly.
1981              Use generate(), construct() or import_key() instead.
1982
1983              Variables
1984
1985                     · n (integer) -- RSA modulus
1986
1987                     · e (integer) -- RSA public exponent
1988
1989                     · d (integer) -- RSA private exponent
1990
1991                     · p (integer) -- First factor of the RSA modulus
1992
1993                     · q (integer) -- Second factor of the RSA modulus
1994
1995                     · u -- Chinese remainder component (p^{-1} ext{mod } q)
1996
1997              exportKey(format='PEM',   passphrase=None,    pkcs=1,    protec‐
1998              tion=None, randfunc=None)
1999                     Export this RSA key.
2000
2001                     Parameters
2002
2003                            · format (string) --
2004
2005                              The format to use for wrapping the key:
2006
2007                              · 'PEM'. (Default) Text encoding, done according
2008                                to RFC1421/RFC1423.
2009
2010                              · 'DER'. Binary encoding.
2011
2012                              · 'OpenSSH'. Textual encoding, done according to
2013                                OpenSSH specification.  Only suitable for pub‐
2014                                lic keys (not private keys).
2015
2016
2017                            · passphrase (string) -- (For private  keys  only)
2018                              The pass phrase used for protecting the output.
2019
2020                            · pkcs (integer) --
2021
2022                              (For  private  keys only) The ASN.1 structure to
2023                              use for serializing the key. Note that  even  in
2024                              case  of  PEM  encoding, there is an inner ASN.1
2025                              DER structure.
2026
2027                              With  pkcs=1  (default),  the  private  key   is
2028                              encoded  in  a  simple PKCS#1 structure (RSAPri‐
2029                              vateKey).
2030
2031                              With pkcs=8, the private key  is  encoded  in  a
2032                              PKCS#8 structure (PrivateKeyInfo).
2033
2034                              NOTE:
2035                                 This  parameter  is ignored for a public key.
2036                                 For DER and PEM, an ASN.1 DER SubjectPublicK‐
2037                                 eyInfo structure is always used.
2038
2039
2040                            · protection (string) --
2041
2042                              (For private keys only) The encryption scheme to
2043                              use for protecting the private key.
2044
2045                              If None (default), the behavior depends on  for‐
2046                              mat:
2047
2048                              · For    'DER',    the   PBKDF2WithHMAC-SHA1And‐
2049                                DES-EDE3-CBC scheme  is  used.  The  following
2050                                operations are performed:
2051
2052                                   1. A 16 byte Triple DES key is derived from
2053                                      the   passphrase   using   Crypto.Proto‐
2054                                      col.KDF.PBKDF2()  with 8 bytes salt, and
2055                                      1 000 iterations of Crypto.Hash.HMAC.
2056
2057                                   2. The private key is encrypted using CBC.
2058
2059                                   3. The encrypted key is  encoded  according
2060                                      to PKCS#8.
2061
2062                              · For  'PEM', the obsolete PEM encryption scheme
2063                                is used.  It is based on MD5 for  key  deriva‐
2064                                tion, and Triple DES for encryption.
2065
2066                              Specifying  a value for protection is only mean‐
2067                              ingful for PKCS#8 (that is, pkcs=8) and only  if
2068                              a pass phrase is present too.
2069
2070                              The  supported  schemes for PKCS#8 are listed in
2071                              the Crypto.IO.PKCS8 module (see wrap_algo param‐
2072                              eter).
2073
2074
2075                            · randfunc  (callable) -- A function that provides
2076                              random bytes. Only used for PEM  encoding.   The
2077                              default is Crypto.Random.get_random_bytes().
2078
2079                     Returns
2080                            the encoded key
2081
2082                     Return type
2083                            byte string
2084
2085                     Raises ValueError  --  when the format is unknown or when
2086                            you try to encrypt a private key with  DER  format
2087                            and PKCS#1.
2088
2089                     WARNING:
2090                        If  you  don't  provide a pass phrase, the private key
2091                        will be exported in the clear!
2092
2093              export_key(format='PEM',   passphrase=None,   pkcs=1,    protec‐
2094              tion=None, randfunc=None)
2095                     Export this RSA key.
2096
2097                     Parameters
2098
2099                            · format (string) --
2100
2101                              The format to use for wrapping the key:
2102
2103                              · 'PEM'. (Default) Text encoding, done according
2104                                to RFC1421/RFC1423.
2105
2106                              · 'DER'. Binary encoding.
2107
2108                              · 'OpenSSH'. Textual encoding, done according to
2109                                OpenSSH specification.  Only suitable for pub‐
2110                                lic keys (not private keys).
2111
2112
2113                            · passphrase (string) -- (For private  keys  only)
2114                              The pass phrase used for protecting the output.
2115
2116                            · pkcs (integer) --
2117
2118                              (For  private  keys only) The ASN.1 structure to
2119                              use for serializing the key. Note that  even  in
2120                              case  of  PEM  encoding, there is an inner ASN.1
2121                              DER structure.
2122
2123                              With  pkcs=1  (default),  the  private  key   is
2124                              encoded  in  a  simple PKCS#1 structure (RSAPri‐
2125                              vateKey).
2126
2127                              With pkcs=8, the private key  is  encoded  in  a
2128                              PKCS#8 structure (PrivateKeyInfo).
2129
2130                              NOTE:
2131                                 This  parameter  is ignored for a public key.
2132                                 For DER and PEM, an ASN.1 DER SubjectPublicK‐
2133                                 eyInfo structure is always used.
2134
2135
2136                            · protection (string) --
2137
2138                              (For private keys only) The encryption scheme to
2139                              use for protecting the private key.
2140
2141                              If None (default), the behavior depends on  for‐
2142                              mat:
2143
2144                              · For    'DER',    the   PBKDF2WithHMAC-SHA1And‐
2145                                DES-EDE3-CBC scheme  is  used.  The  following
2146                                operations are performed:
2147
2148                                   1. A 16 byte Triple DES key is derived from
2149                                      the   passphrase   using   Crypto.Proto‐
2150                                      col.KDF.PBKDF2()  with 8 bytes salt, and
2151                                      1 000 iterations of Crypto.Hash.HMAC.
2152
2153                                   2. The private key is encrypted using CBC.
2154
2155                                   3. The encrypted key is  encoded  according
2156                                      to PKCS#8.
2157
2158                              · For  'PEM', the obsolete PEM encryption scheme
2159                                is used.  It is based on MD5 for  key  deriva‐
2160                                tion, and Triple DES for encryption.
2161
2162                              Specifying  a value for protection is only mean‐
2163                              ingful for PKCS#8 (that is, pkcs=8) and only  if
2164                              a pass phrase is present too.
2165
2166                              The  supported  schemes for PKCS#8 are listed in
2167                              the Crypto.IO.PKCS8 module (see wrap_algo param‐
2168                              eter).
2169
2170
2171                            · randfunc  (callable) -- A function that provides
2172                              random bytes. Only used for PEM  encoding.   The
2173                              default is Crypto.Random.get_random_bytes().
2174
2175                     Returns
2176                            the encoded key
2177
2178                     Return type
2179                            byte string
2180
2181                     Raises ValueError  --  when the format is unknown or when
2182                            you try to encrypt a private key with  DER  format
2183                            and PKCS#1.
2184
2185                     WARNING:
2186                        If  you  don't  provide a pass phrase, the private key
2187                        will be exported in the clear!
2188
2189              has_private()
2190                     Whether this is an RSA private key
2191
2192              publickey()
2193                     A matching RSA public key.
2194
2195                     Returns
2196                            a new RsaKey object
2197
2198              size_in_bits()
2199                     Size of the RSA modulus in bits
2200
2201              size_in_bytes()
2202                     The minimal amount of bytes that can hold the RSA modulus
2203
2204       Crypto.PublicKey.RSA.oid = '1.2.840.113549.1.1.1'
2205              Object ID for the RSA encryption algorithm. This OID often indi‐
2206              cates  a  generic  RSA  key, even when such key will be actually
2207              used for digital signatures.
2208
2209   DSA
2210       DSA is a widespread public key signature  algorithm.  Its  security  is
2211       based  on the discrete logarithm problem (DLP). Given a cyclic group, a
2212       generator g, and an element h, it is hard to find  an  integer  x  such
2213       that  g^x = h. The problem is believed to be difficult, and it has been
2214       proved such (and therefore secure) for more than 30 years.
2215
2216       The group is actually a sub-group over the integers modulo  p,  with  p
2217       prime.   The  sub-group order is q, which is prime too; it always holds
2218       that (p-1) is a multiple of q.  The cryptographic strength is linked to
2219       the magnitude of p and q.  The signer holds a value x (0<x<q-1) as pri‐
2220       vate key, and its public key (y where y=g^x ext{ mod } p)  is  distrib‐
2221       uted.
2222
2223       In 2017, a sufficient size is deemed to be 2048 bits for p and 256 bits
2224       for q.  For more information, see the most recent ECRYPT report.
2225
2226       The algorithm can only be used for authentication (digital  signature).
2227       DSA cannot be used for confidentiality (encryption).
2228
2229       The values (p,q,g) are called domain parameters; they are not sensitive
2230       but must be shared by both parties (the signer and the verifier).  Dif‐
2231       ferent  signers  can  share the same domain parameters with no security
2232       concerns.
2233
2234       The DSA signature is twice as big as the size of q (64 bytes  if  q  is
2235       256 bit long).
2236
2237       This  module  provides  facilities  for generating new DSA keys and for
2238       constructing them from known components.
2239
2240       As an example, this is how you generate a new DSA key  pair,  save  the
2241       public  key  in  a  file  called  public_key.pem,  sign a message (with
2242       Crypto.Signature.DSS), and verify it:
2243
2244          >>> from Crypto.PublicKey import DSA
2245          >>> from Crypto.Signature import DSS
2246          >>> from Crypto.Hash import SHA256
2247          >>>
2248          >>> # Create a new DSA key
2249          >>> key = DSA.generate(2048)
2250          >>> f = open("public_key.pem", "w")
2251          >>> f.write(key.publickey().export_key())
2252          >>> f.close()
2253          >>>
2254          >>> # Sign a message
2255          >>> message = b"Hello"
2256          >>> hash_obj = SHA256.new(message)
2257          >>> signer = DSS.new(key, 'fips-186-3')
2258          >>> signature = signer.sign(hash_obj)
2259          >>>
2260          >>> # Load the public key
2261          >>> f = open("public_key.pem", "r")
2262          >>> hash_obj = SHA256.new(message)
2263          >>> pub_key = DSA.import_key(f.read())
2264          >>> verifier = DSS.new(pub_key, 'fips-186-3')
2265          >>>
2266          >>> # Verify the authenticity of the message
2267          >>> try:
2268          >>>     verifier.verify(hash_obj, signature)
2269          >>>     print "The message is authentic."
2270          >>> except ValueError:
2271          >>>     print "The message is not authentic."
2272
2273       Crypto.PublicKey.DSA.generate(bits, randfunc=None, domain=None)
2274              Generate a new DSA key pair.
2275
2276              The algorithm follows Appendix A.1/A.2 and B.1  of  FIPS  186-4,
2277              respectively for domain generation and key pair generation.
2278
2279              Parameters
2280
2281                     · bits  (integer) -- Key length, or size (in bits) of the
2282                       DSA modulus p.  It must be 1024, 2048 or 3072.
2283
2284                     · randfunc (callable) -- Random number  generation  func‐
2285                       tion; it accepts a single integer N and return a string
2286                       of  random  data  N  bytes  long.   If  not  specified,
2287                       Crypto.Random.get_random_bytes() is used.
2288
2289                     · domain  (tuple) -- The DSA domain parameters p, q and g
2290                       as a list of 3 integers. Size of p and q must comply to
2291                       FIPS  186-4.  If not specified, the parameters are cre‐
2292                       ated anew.
2293
2294              Returns
2295                     a new DSA key object
2296
2297              Return type
2298                     DsaKey
2299
2300              Raises ValueError -- when bits is too little, too big, or not  a
2301                     multiple of 64.
2302
2303       Crypto.PublicKey.DSA.construct(tup, consistency_check=True)
2304              Construct a DSA key from a tuple of valid DSA components.
2305
2306              Parameters
2307
2308                     · tup (tuple) --
2309
2310                       A tuple of long integers, with 4 or 5 items in the fol‐
2311                       lowing order:
2312
2313                          1. Public key (y).
2314
2315                          2. Sub-group generator (g).
2316
2317                          3. Modulus, finite field order (p).
2318
2319                          4. Sub-group order (q).
2320
2321                          5. Private key (x). Optional.
2322
2323
2324                     · consistency_check (boolean) --  If  True,  the  library
2325                       will  verify  that  the  provided components fulfil the
2326                       main DSA properties.
2327
2328              Raises ValueError -- when the key being imported fails the  most
2329                     basic DSA validity checks.
2330
2331              Returns
2332                     a DSA key object
2333
2334              Return type
2335                     DsaKey
2336
2337       class Crypto.PublicKey.DSA.DsaKey(key_dict)
2338              Class  defining an actual DSA key.  Do not instantiate directly.
2339              Use generate(), construct() or import_key() instead.
2340
2341              Variables
2342
2343                     · p (integer) -- DSA modulus
2344
2345                     · q (integer) -- Order of the subgroup
2346
2347                     · g (integer) -- Generator
2348
2349                     · y (integer) -- Public key
2350
2351                     · x (integer) -- Private key
2352
2353              domain()
2354                     The DSA domain parameters.
2355
2356                     Returns
2357                            tuple : (p,q,g)
2358
2359              exportKey(format='PEM',  pkcs8=None,  passphrase=None,   protec‐
2360              tion=None, randfunc=None)
2361                     Export this DSA key.
2362
2363                     Parameters
2364
2365                            · format (string) --
2366
2367                              The encoding for the output:
2368
2369                              · 'PEM'   (default).   ASCII   as  per  RFC1421/
2370                                RFC1423.
2371
2372                              · 'DER'. Binary ASN.1 encoding.
2373
2374                              · 'OpenSSH'. ASCII  one-liner  as  per  RFC4253.
2375                                Only suitable for public keys, not for private
2376                                keys.
2377
2378
2379                            · passphrase (string) -- Private  keys  only.  The
2380                              pass phrase to protect the output.
2381
2382                            · pkcs8  (boolean)  --  Private keys only. If True
2383                              (default), the key is encoded  with  PKCS#8.  If
2384                              False,    it    is   encoded   in   the   custom
2385                              OpenSSL/OpenSSH container.
2386
2387                            · protection (string) --
2388
2389                              Only in combination with  a  pass  phrase.   The
2390                              encryption scheme to use to protect the output.
2391
2392                              If  pkcs8  takes  value True, this is the PKCS#8
2393                              algorithm to use for  deriving  the  secret  and
2394                              encrypting  the private DSA key.  For a complete
2395                              list of algorithms,  see  Crypto.IO.PKCS8.   The
2396                              default is PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC.
2397
2398                              If  pkcs8  is False, the obsolete PEM encryption
2399                              scheme is used. It  is  based  on  MD5  for  key
2400                              derivation,   and  Triple  DES  for  encryption.
2401                              Parameter protection is then ignored.
2402
2403                              The combination format='DER' and pkcs8=False  is
2404                              not allowed if a passphrase is present.
2405
2406
2407                            · randfunc  (callable)  -- A function that returns
2408                              random bytes.   By  default  it  is  Crypto.Ran‐
2409                              dom.get_random_bytes().
2410
2411                     Returns
2412                            the encoded key
2413
2414                     Return type
2415                            byte string
2416
2417                     Raises ValueError  --  when the format is unknown or when
2418                            you try to encrypt a private key with  DER  format
2419                            and OpenSSL/OpenSSH.
2420
2421                     WARNING:
2422                        If  you  don't  provide a pass phrase, the private key
2423                        will be exported in the clear!
2424
2425              export_key(format='PEM',  pkcs8=None,  passphrase=None,  protec‐
2426              tion=None, randfunc=None)
2427                     Export this DSA key.
2428
2429                     Parameters
2430
2431                            · format (string) --
2432
2433                              The encoding for the output:
2434
2435                              · 'PEM'   (default).   ASCII   as  per  RFC1421/
2436                                RFC1423.
2437
2438                              · 'DER'. Binary ASN.1 encoding.
2439
2440                              · 'OpenSSH'. ASCII  one-liner  as  per  RFC4253.
2441                                Only suitable for public keys, not for private
2442                                keys.
2443
2444
2445                            · passphrase (string) -- Private  keys  only.  The
2446                              pass phrase to protect the output.
2447
2448                            · pkcs8  (boolean)  --  Private keys only. If True
2449                              (default), the key is encoded  with  PKCS#8.  If
2450                              False,    it    is   encoded   in   the   custom
2451                              OpenSSL/OpenSSH container.
2452
2453                            · protection (string) --
2454
2455                              Only in combination with  a  pass  phrase.   The
2456                              encryption scheme to use to protect the output.
2457
2458                              If  pkcs8  takes  value True, this is the PKCS#8
2459                              algorithm to use for  deriving  the  secret  and
2460                              encrypting  the private DSA key.  For a complete
2461                              list of algorithms,  see  Crypto.IO.PKCS8.   The
2462                              default is PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC.
2463
2464                              If  pkcs8  is False, the obsolete PEM encryption
2465                              scheme is used. It  is  based  on  MD5  for  key
2466                              derivation,   and  Triple  DES  for  encryption.
2467                              Parameter protection is then ignored.
2468
2469                              The combination format='DER' and pkcs8=False  is
2470                              not allowed if a passphrase is present.
2471
2472
2473                            · randfunc  (callable)  -- A function that returns
2474                              random bytes.   By  default  it  is  Crypto.Ran‐
2475                              dom.get_random_bytes().
2476
2477                     Returns
2478                            the encoded key
2479
2480                     Return type
2481                            byte string
2482
2483                     Raises ValueError  --  when the format is unknown or when
2484                            you try to encrypt a private key with  DER  format
2485                            and OpenSSL/OpenSSH.
2486
2487                     WARNING:
2488                        If  you  don't  provide a pass phrase, the private key
2489                        will be exported in the clear!
2490
2491              has_private()
2492                     Whether this is a DSA private key
2493
2494              publickey()
2495                     A matching DSA public key.
2496
2497                     Returns
2498                            a new DsaKey object
2499
2500       Crypto.PublicKey.DSA.import_key(extern_key, passphrase=None)
2501              Import a DSA key.
2502
2503              Parameters
2504
2505                     · extern_key (string or byte string) --
2506
2507                       The DSA key to import.
2508
2509                       The following formats are supported for  a  DSA  public
2510                       key:
2511
2512                       · X.509 certificate (binary DER or PEM)
2513
2514                       · X.509 subjectPublicKeyInfo (binary DER or PEM)
2515
2516                       · OpenSSH (ASCII one-liner, see RFC4253)
2517
2518                       The  following  formats are supported for a DSA private
2519                       key:
2520
2521                       · PKCS#8 PrivateKeyInfo or EncryptedPrivateKeyInfo  DER
2522                         SEQUENCE (binary or PEM)
2523
2524                       · OpenSSL/OpenSSH custom format (binary or PEM)
2525
2526                       For  details  about  the  PEM  encoding,  see RFC1421/‐
2527                       RFC1423.
2528
2529
2530                     · passphrase (string) --
2531
2532                       In case of an encrypted private key, this is  the  pass
2533                       phrase from which the decryption key is derived.
2534
2535                       Encryption  may  be  applied either at the PKCS#8 or at
2536                       the PEM level.
2537
2538
2539              Returns
2540                     a DSA key object
2541
2542              Return type
2543                     DsaKey
2544
2545              Raises ValueError -- when the given key cannot be parsed (possi‐
2546                     bly because the pass phrase is wrong).
2547
2548   ECC
2549       ECC  (Elliptic  Curve  Cryptography)  is a modern and efficient type of
2550       public key cryptography.  Its security is based on  the  difficulty  to
2551       solve  discrete  logarithms  on the field defined by specific equations
2552       computed over a curve.
2553
2554       ECC can be used to create  digital  signatures  or  to  perform  a  key
2555       exchange.
2556
2557       Compared  to  traditional  algorithms  like RSA, an ECC key is signifi‐
2558       cantly smaller at the same security level.  For  instance,  a  3072-bit
2559       RSA  key  takes 768 bytes whereas the equally strong NIST P-256 private
2560       key only takes 32 bytes (that is, 256 bits).
2561
2562       This module provides mechanisms for generating new ECC keys,  exporting
2563       and importing them using widely supported formats like PEM or DER.
2564
2565                      ┌───────────┬────────────────────────────┐
2566                      │Curve      │ Possible identifiers       │
2567                      ├───────────┼────────────────────────────┤
2568                      │NIST P-256 │ 'NIST    P-256',   'p256', │
2569                      │           │ 'P-256',     'prime256v1', │
2570                      │           │ 'secp256r1'                
2571                      ├───────────┼────────────────────────────┤
2572                      │NIST P-384 │ 'NIST    P-384',   'p384', │
2573                      │           │ 'P-384',     'prime384v1', │
2574                      │           │ 'secp384r1'                
2575                      ├───────────┼────────────────────────────┤
2576                      │NIST P-521 │ 'NIST    P-521',   'p521', │
2577                      │           │ 'P-521',     'prime521v1', │
2578                      │           │ 'secp521r1'                
2579                      └───────────┴────────────────────────────┘
2580
2581       For  more  information  about  each  NIST curve see FIPS 186-4, Section
2582       D.1.2.
2583
2584       The following example demonstrates how  to  generate  a  new  ECC  key,
2585       export it, and subsequentely reload it back into the application:
2586
2587          >>> from Crypto.PublicKey import ECC
2588          >>>
2589          >>> key = ECC.generate(curve='P-256')
2590          >>>
2591          >>> f = open('myprivatekey.pem','wt')
2592          >>> f.write(key.export_key()
2593          >>> f.close()
2594          ...
2595          >>> f = open('myprivatekey.pem','rt')
2596          >>> key = ECC.import_key(f.read())
2597
2598       The  ECC  key  can be used to perform or verify ECDSA signatures, using
2599       the module Crypto.Signature.DSS.
2600
2601       class Crypto.PublicKey.ECC.EccKey(**kwargs)
2602              Class defining an ECC key.  Do not  instantiate  directly.   Use
2603              generate(), construct() or import_key() instead.
2604
2605              Variables
2606
2607                     · curve (string) -- The name of the ECC as defined in Ta‐
2608                       ble %s.
2609
2610                     · pointQ (EccPoint) -- an ECC  point  representating  the
2611                       public component
2612
2613                     · d (integer) -- A scalar representating the private com‐
2614                       ponent
2615
2616              export_key(**kwargs)
2617                     Export this ECC key.
2618
2619                     Parameters
2620
2621                            · format (string) --
2622
2623                              The format to use for encoding the key:
2624
2625                              · 'DER'. The key will be encoded  in  ASN.1  DER
2626                                format  (binary).  For a public key, the ASN.1
2627                                subjectPublicKeyInfo  structure   defined   in
2628                                RFC5480  will be used.  For a private key, the
2629                                ASN.1  ECPrivateKey   structure   defined   in
2630                                RFC5915  is  used  instead  (possibly within a
2631                                PKCS#8  envelope,  see  the   use_pkcs8   flag
2632                                below).
2633
2634                              · 'PEM'.  The key will be encoded in a PEM enve‐
2635                                lope (ASCII).
2636
2637                              · 'OpenSSH'. The key  will  be  encoded  in  the
2638                                OpenSSH format (ASCII, public keys only).
2639
2640
2641                            · passphrase   (byte  string  or  string)  --  The
2642                              passphrase to use  for  protecting  the  private
2643                              key.
2644
2645                            · use_pkcs8 (boolean) --
2646
2647                              Only relevant for private keys.
2648
2649                              If  True  (default  and recommended), the PKCS#8
2650                              representation will be used.
2651
2652                              If False, the much weaker PEM encryption  mecha‐
2653                              nism will be used.
2654
2655
2656                            · protection  (string)  --  When  a private key is
2657                              exported  with  password-protection  and  PKCS#8
2658                              (both  DER and PEM formats), this parameter MUST
2659                              be present and be a valid algorithm supported by
2660                              Crypto.IO.PKCS8.    It  is  recommended  to  use
2661                              PBKDF2WithHMAC-SHA1AndAES128-CBC.
2662
2663                            · compress (boolean) --
2664
2665                              If True, a more compact  representation  of  the
2666                              public key with the X-coordinate only is used.
2667
2668                              If  False (default), the full public key will be
2669                              exported.
2670
2671
2672                     WARNING:
2673                        If you don't provide a  passphrase,  the  private  key
2674                        will be exported in the clear!
2675
2676                     NOTE:
2677                        When  exporting a private key with password-protection
2678                        and PKCS#8 (both  DER  and  PEM  formats),  any  extra
2679                        parameters   to   export_key()   will   be  passed  to
2680                        Crypto.IO.PKCS8.
2681
2682                     Returns
2683                            A multi-line string (for PEM and OpenSSH) or bytes
2684                            (for DER) with the encoded key.
2685
2686              has_private()
2687                     True  if  this  key  can be used for making signatures or
2688                     decrypting data.
2689
2690              public_key()
2691                     A matching ECC public key.
2692
2693                     Returns
2694                            a new EccKey object
2695
2696       class Crypto.PublicKey.ECC.EccPoint(x, y, curve='p256')
2697              A class to abstract a point over an Elliptic Curve.
2698
2699              The class support special methods for:
2700
2701              · Adding two points: R = S + T
2702
2703              · In-place addition: S += T
2704
2705              · Negating a point: R = -T
2706
2707              · Comparing two points: if S == T: ...
2708
2709              · Multiplying a point by a scalar: R = S*k
2710
2711              · In-place multiplication by a scalar: T *= k
2712
2713              Variables
2714
2715                     · x (integer) -- The affine X-coordinate of the ECC point
2716
2717                     · y (integer) -- The affine Y-coordinate of the ECC point
2718
2719                     · xy -- The tuple with X- and Y- coordinates
2720
2721              copy() Return a copy of this point.
2722
2723              double()
2724                     Double this point (in-place operation).
2725
2726                     Return EccPoint : this same object (to enable chaining)
2727
2728              is_point_at_infinity()
2729                     True if this is the point-at-infinity.
2730
2731              point_at_infinity()
2732                     Return the point-at-infinity for the curve this point  is
2733                     on.
2734
2735              size_in_bits()
2736                     Size of each coordinate, in bits.
2737
2738              size_in_bytes()
2739                     Size of each coordinate, in bytes.
2740
2741       exception Crypto.PublicKey.ECC.UnsupportedEccFeature
2742
2743       Crypto.PublicKey.ECC.construct(**kwargs)
2744              Build  a new ECC key (private or public) starting from some base
2745              components.
2746
2747              Parameters
2748
2749                     · curve (string) -- Mandatory. It must be  a  curve  name
2750                       defined in Table %s.
2751
2752                     · d  (integer)  --  Only for a private key. It must be in
2753                       the range [1..order-1].
2754
2755                     · point_x (integer) -- Mandatory  for  a  public  key.  X
2756                       coordinate (affine) of the ECC point.
2757
2758                     · point_y  (integer)  --  Mandatory  for  a public key. Y
2759                       coordinate (affine) of the ECC point.
2760
2761              Returns
2762                     a new ECC key object
2763
2764              Return type
2765                     EccKey
2766
2767       Crypto.PublicKey.ECC.generate(**kwargs)
2768              Generate a new private key on the given curve.
2769
2770              Parameters
2771
2772                     · curve (string) -- Mandatory. It must be  a  curve  name
2773                       defined in Table %s.
2774
2775                     · randfunc  (callable)  -- Optional. The RNG to read ran‐
2776                       domness   from.    If   None,    Crypto.Random.get_ran‐
2777                       dom_bytes() is used.
2778
2779       Crypto.PublicKey.ECC.import_key(encoded, passphrase=None)
2780              Import an ECC key (public or private).
2781
2782              Parameters
2783
2784                     · encoded (bytes or multi-line string) --
2785
2786                       The ECC key to import.
2787
2788                       An ECC public key can be:
2789
2790                       · An X.509 certificate, binary (DER) or ASCII (PEM)
2791
2792                       · An  X.509 subjectPublicKeyInfo, binary (DER) or ASCII
2793                         (PEM)
2794
2795                       · An OpenSSH line (e.g. the content of ~/.ssh/id_ecdsa,
2796                         ASCII)
2797
2798                       An ECC private key can be:
2799
2800                       · In  binary  format  (DER, see section 3 of RFC5915 or
2801                         PKCS#8)
2802
2803                       · In ASCII format (PEM or OpenSSH)
2804
2805                       Private keys can be in the clear or password-protected.
2806
2807                       For details  about  the  PEM  encoding,  see  RFC1421/‐
2808                       RFC1423.
2809
2810
2811                     · passphrase  (byte  string) -- The passphrase to use for
2812                       decrypting a private key.  Encryption  may  be  applied
2813                       protected  at  the  PEM  level  or at the PKCS#8 level.
2814                       This parameter is ignored if the key in  input  is  not
2815                       encrypted.
2816
2817              Returns
2818                     a new ECC key object
2819
2820              Return type
2821                     EccKey
2822
2823              Raises ValueError -- when the given key cannot be parsed (possi‐
2824                     bly because the pass phrase is wrong).
2825
2826       · RSA keys
2827
2828       · DSA keys
2829
2830       · Elliptic Curve keys
2831
2832   Obsolete key type
2833   El Gamal
2834       WARNING:
2835          Even though ElGamal algorithms are in theory reasonably  secure,  in
2836          practice  there  are  no  real  good  reasons  to prefer them to rsa
2837          instead.
2838
2839   Signature algorithm
2840       The security of the ElGamal signature scheme is based (like DSA) on the
2841       discrete  logarithm problem (DLP). Given a cyclic group, a generator g,
2842       and an element h, it is hard to find an integer x such that g^x = h.
2843
2844       The group is the largest multiplicative sub-group of the integers  mod‐
2845       ulo  p,  with p prime.  The signer holds a value x (0<x<p-1) as private
2846       key, and its public key (y where y=g^x ext{ mod } p) is distributed.
2847
2848       The ElGamal signature is twice as big as p.
2849
2850   Encryption algorithm
2851       The security of the ElGamal encryption scheme is based on the  computa‐
2852       tional  Diffie-Hellman problem (CDH). Given a cyclic group, a generator
2853       g, and two integers a and b, it is difficult to find the element g^{ab}
2854       when only g^a and g^b are known, and not a and b.
2855
2856       As  before,  the  group  is the largest multiplicative sub-group of the
2857       integers modulo p,  with  p  prime.   The  receiver  holds  a  value  a
2858       (0<a<p-1)  as  private key, and its public key (b where b=g^a) is given
2859       to the sender.
2860
2861       The ElGamal ciphertext is twice as big as p.
2862
2863   Domain parameters
2864       For both signature and encryption schemes, the values (p,g) are  called
2865       domain  parameters.   They are not sensitive but must be distributed to
2866       all parties (senders and receivers).  Different signers can  share  the
2867       same  domain  parameters, as can different recipients of encrypted mes‐
2868       sages.
2869
2870   Security
2871       Both DLP and CDH problem are believed to be difficult,  and  they  have
2872       been proved such (and therefore secure) for more than 30 years.
2873
2874       The cryptographic strength is linked to the magnitude of p.  In 2017, a
2875       sufficient size for p is deemed to be 2048 bits.  For more information,
2876       see the most recent ECRYPT report.
2877
2878       The  signature  is  four  times larger than the equivalent DSA, and the
2879       ciphertext is two times larger than the equivalent RSA.
2880
2881   Functionality
2882       This module provides facilities for generating  new  ElGamal  keys  and
2883       constructing them from known components.
2884
2885       Crypto.PublicKey.ElGamal.generate(bits, randfunc)
2886              Randomly generate a fresh, new ElGamal key.
2887
2888              The  key  will be safe for use for both encryption and signature
2889              (although it should be used for only one purpose).
2890
2891              Parameters
2892
2893                     · bits (int) -- Key length, or size (in bits) of the mod‐
2894                       ulus p.  The recommended value is 2048.
2895
2896                     · randfunc  (callable)  -- Random number generation func‐
2897                       tion; it should accept a single integer N and return  a
2898                       string of random N random bytes.
2899
2900              Returns
2901                     an ElGamalKey object
2902
2903       Crypto.PublicKey.ElGamal.construct(tup)
2904              Construct  an  ElGamal  key from a tuple of valid ElGamal compo‐
2905              nents.
2906
2907              The modulus p must be a prime.  The  following  conditions  must
2908              apply:
2909
2910
2911
2912              Parameters
2913                     tup (tuple) --
2914
2915                     A  tuple  with  either  3 or 4 integers, in the following
2916                     order:
2917
2918                     1. Modulus (p).
2919
2920                     2. Generator (g).
2921
2922                     3. Public key (y).
2923
2924                     4. Private key (x). Optional.
2925
2926
2927              Raises ValueError -- when the key being imported fails the  most
2928                     basic ElGamal validity checks.
2929
2930              Returns
2931                     an ElGamalKey object
2932
2933       class Crypto.PublicKey.ElGamal.ElGamalKey(randfunc=None)
2934              Class  defining  an  ElGamal  key.  Do not instantiate directly.
2935              Use generate() or construct() instead.
2936
2937              Variables
2938
2939                     · p -- Modulus
2940
2941                     · g -- Generator
2942
2943                     · y (integer) -- Public key component
2944
2945                     · x (integer) -- Private key component
2946
2947              has_private()
2948                     Whether this is an ElGamal private key
2949
2950              publickey()
2951                     A matching ElGamal public key.
2952
2953                     Returns
2954                            a new ElGamalKey object
2955
2956       · ElGamal keys
2957
2958   Crypto.Protocol package
2959   Key Derivation Functions
2960       This module contains a collection of standard key derivation functions.
2961
2962       A key derivation function derives one or  more  secondary  secret  keys
2963       from one primary secret (a master key or a pass phrase).
2964
2965       This  is typically done to insulate the secondary keys from each other,
2966       to avoid that leakage of a secondary key compromises  the  security  of
2967       the  master key, or to thwart attacks on pass phrases (e.g. via rainbow
2968       tables).
2969
2970       Crypto.Protocol.KDF.HKDF(master, key_len,  salt,  hashmod,  num_keys=1,
2971       context=None)
2972              Derive  one  or  more  keys  from  a  master  secret  using  the
2973              HMAC-based KDF defined in RFC5869.
2974
2975              This KDF is not suitable for deriving keys from  a  password  or
2976              for key stretching. Use PBKDF2() instead.
2977
2978              HKDF is a key derivation method approved by NIST in SP 800 56C.
2979
2980              Parameters
2981
2982                     · master  (byte  string) -- The unguessable value used by
2983                       the KDF to generate the  other  keys.   It  must  be  a
2984                       high-entropy  secret,  though  not necessarily uniform.
2985                       It must not be a password.
2986
2987                     · salt (byte string) -- A non-secret, reusable value that
2988                       strengthens  the  randomness extraction step.  Ideally,
2989                       it is as long as the digest size of  the  chosen  hash.
2990                       If empty, a string of zeroes in used.
2991
2992                     · key_len  (integer)  --  The  length  in  bytes of every
2993                       derived key.
2994
2995                     · hashmod (module) -- A cryptographic hash algorithm from
2996                       Crypto.Hash.  Crypto.Hash.SHA512 is a good choice.
2997
2998                     · num_keys  (integer)  --  The  number of keys to derive.
2999                       Every key is key_len bytes long.  The  maximum  cumula‐
3000                       tive length of all keys is 255 times the digest size.
3001
3002                     · context (byte string) -- Optional identifier describing
3003                       what the keys are used for.
3004
3005              Returns
3006                     A byte string or a tuple of byte strings.
3007
3008       Crypto.Protocol.KDF.PBKDF1(password,    salt,    dkLen,     count=1000,
3009       hashAlgo=None)
3010              Derive one key from a password (or passphrase).
3011
3012              This  function  performs key derivation according to an old ver‐
3013              sion of the PKCS#5 standard (v1.5) or RFC2898.
3014
3015              WARNING:
3016                 Newer applications should use the more secure  and  versatile
3017                 PBKDF2() instead.
3018
3019              Parameters
3020
3021                     · password  (string)  --  The secret password to generate
3022                       the key from.
3023
3024                     · salt (byte string) -- An 8 byte string to use for  bet‐
3025                       ter  protection  from  dictionary  attacks.  This value
3026                       does not need to be kept secret, but it should be  ran‐
3027                       domly chosen for each derivation.
3028
3029                     · dkLen  (integer)  -- The length of the desired key. The
3030                       default  is  16  bytes,  suitable  for   instance   for
3031                       Crypto.Cipher.AES.
3032
3033                     · count  (integer)  --  The number of iterations to carry
3034                       out. The recommendation is 1000 or more.
3035
3036                     · hashAlgo (module) -- The hash algorithm to  use,  as  a
3037                       module  or an object from the Crypto.Hash package.  The
3038                       digest length must  be  no  shorter  than  dkLen.   The
3039                       default algorithm is Crypto.Hash.SHA1.
3040
3041              Returns
3042                     A byte string of length dkLen that can be used as key.
3043
3044       Crypto.Protocol.KDF.PBKDF2(password,    salt,   dkLen=16,   count=1000,
3045       prf=None, hmac_hash_module=None)
3046              Derive one or more keys from a password (or passphrase).
3047
3048              This function performs key derivation according  to  the  PKCS#5
3049              standard (v2.0).
3050
3051              Parameters
3052
3053                     · password (string or byte string) -- The secret password
3054                       to generate the key from.
3055
3056                     · salt (string or byte string) -- A (byte) string to  use
3057                       for  better  protection  from dictionary attacks.  This
3058                       value does not need to be kept secret, but it should be
3059                       randomly  chosen for each derivation. It is recommended
3060                       to be at least 8 bytes long.
3061
3062                     · dkLen (integer) -- The cumulative length of the desired
3063                       keys.
3064
3065                     · count  (integer)  --  The number of iterations to carry
3066                       out.
3067
3068                     · prf (callable) -- A pseudorandom function. It must be a
3069                       function  that  returns  a pseudorandom string from two
3070                       parameters: a secret and  a  salt.  If  not  specified,
3071                       HMAC-SHA1 is used.
3072
3073                     · hmac_hash_module  (module) -- A module from Crypto.Hash
3074                       implementing a Merkle-Damgard cryptographic hash, which
3075                       PBKDF2 must use in combination with HMAC.  This parame‐
3076                       ter is mutually exclusive with prf.
3077
3078              Returns
3079                     A byte string of length dkLen that can  be  used  as  key
3080                     material.   If  you  wanted  multiple keys, just break up
3081                     this string into segments of the desired length.
3082
3083       Crypto.Protocol.KDF.scrypt(password,   salt,   key_len,   N,   r,    p,
3084       num_keys=1)
3085              Derive one or more keys from a passphrase.
3086
3087              This  function  performs  key derivation according to the scrypt
3088              algorithm, introduced in Percival's paper "Stronger key  deriva‐
3089              tion via sequential memory-hard functions".
3090
3091              This implementation is based on RFC7914.
3092
3093              Parameters
3094
3095                     · password (string) -- The secret pass phrase to generate
3096                       the keys from.
3097
3098                     · salt (string) -- A string to use for better  protection
3099                       from  dictionary  attacks.  This value does not need to
3100                       be kept secret, but it should be  randomly  chosen  for
3101                       each  derivation.   It  is recommended to be at least 8
3102                       bytes long.
3103
3104                     · key_len (integer) --  The  length  in  bytes  of  every
3105                       derived key.
3106
3107                     · N  (integer) -- CPU/Memory cost parameter. It must be a
3108                       power of 2 and less than 2^{32}.
3109
3110                     · r (integer) -- Block size parameter.
3111
3112                     · p (integer) -- Parallelization parameter.  It  must  be
3113                       no greater than (2^{32}-1)/(4r).
3114
3115                     · num_keys  (integer)  --  The  number of keys to derive.
3116                       Every key is key_len bytes long.  By  default,  only  1
3117                       key is generated.  The maximum cumulative length of all
3118                       keys is (2^{32}-1)*32 (that is, 128TB).
3119
3120              A good choice of parameters (N, r , p) was  suggested  by  Colin
3121              Percival in his presentation in 2009:
3122
3123              · (16384, 8, 1) for interactive logins (<=100ms)
3124
3125              · (1048576, 8, 1) for file encryption (<=5s)
3126
3127              Returns
3128                     A byte string or a tuple of byte strings.
3129
3130   Secret Sharing Schemes
3131       This file implements secret sharing protocols.
3132
3133       In  a  (k,  n) secret sharing protocol, a honest dealer breaks a secret
3134       into multiple shares that are distributed amongst n players.
3135
3136       The protocol guarantees  that  nobody  can  learn  anything  about  the
3137       secret, unless k players gather together to assemble their shares.
3138
3139       class Crypto.Protocol.SecretSharing.Shamir
3140              Shamir's secret sharing scheme.
3141
3142              This  class  implements  the  Shamir's  secret  sharing protocol
3143              described in his original paper "How to share a secret".
3144
3145              All shares are points over a 2-dimensional  curve.  At  least  k
3146              points  (that is, shares) are required to reconstruct the curve,
3147              and therefore the secret.
3148
3149              This implementation is primarilly meant to protect AES128  keys.
3150              To  that  end,  the secret is associated to a curve in the field
3151              GF(2^128) defined by the irreducible polynomial x^{128} + x^7  +
3152              x^2  +  x + 1 (the same used in AES-GCM).  The shares are always
3153              16 bytes long.
3154
3155              Data produced by this implementation are compatible to the popu‐
3156              lar ssss tool if used with 128 bit security (parameter "-s 128")
3157              and no dispersion (parameter "-D").
3158
3159              As an example, the following code shows how to  protect  a  file
3160              meant  for  5 people, in such a way that 2 of the 5 are required
3161              to reassemble it:
3162
3163                 >>> from binascii import hexlify
3164                 >>> from Crypto.Cipher import AES
3165                 >>> from Crypto.Random import get_random_bytes
3166                 >>> from Crypto.Protocol.secret_sharing import Shamir
3167                 >>>
3168                 >>> key = get_random_bytes(16)
3169                 >>> shares = Shamir.split(2, 5, key)
3170                 >>> for idx, share in shares:
3171                 >>>     print "Index #%d: %s" % (idx, hexlify(share))
3172                 >>>
3173                 >>> fi = open("clear_file.txt", "rb")
3174                 >>> fo = open("enc_file.txt", "wb")
3175                 >>>
3176                 >>> cipher = AES.new(key, AES.MODE_EAX)
3177                 >>> ct, tag = cipher.encrypt(fi.read()), cipher.digest()
3178                 >>> fo.write(nonce + tag + ct)
3179
3180              Each person can be given one share and the encrypted file.
3181
3182              When 2 people gather together with their shares, the can decrypt
3183              the file:
3184
3185                 >>> from binascii import unhexlify
3186                 >>> from Crypto.Cipher import AES
3187                 >>> from Crypto.Protocol.secret_sharing import Shamir
3188                 >>>
3189                 >>> shares = []
3190                 >>> for x in range(2):
3191                 >>>     in_str = raw_input("Enter index and share separated by comma: ")
3192                 >>>     idx, share = [ strip(s) for s in in_str.split(",") ]
3193                 >>>     shares.append((idx, unhexlify(share)))
3194                 >>> key = Shamir.combine(shares)
3195                 >>>
3196                 >>> fi = open("enc_file.txt", "rb")
3197                 >>> nonce, tag = [ fi.read(16) for x in range(2) ]
3198                 >>> cipher = AES.new(key, AES.MODE_EAX, nonce)
3199                 >>> try:
3200                 >>>     result = cipher.decrypt(fi.read())
3201                 >>>     cipher.verify(tag)
3202                 >>>     with open("clear_file2.txt", "wb") as fo:
3203                 >>>         fo.write(result)
3204                 >>> except ValueError:
3205                 >>>     print "The shares were incorrect"
3206
3207              ATTENTION:
3208                 Reconstruction  does not guarantee that the result is authen‐
3209                 tic.  In particular, a malicious participant  in  the  scheme
3210                 has  the  ability  to force an algebric transformation on the
3211                 result by manipulating her share.
3212
3213                 It is important to use the  scheme  in  combination  with  an
3214                 authentication  mechanism  (the  EAX cipher mode in the exam‐
3215                 ple).
3216
3217              static combine(shares)
3218                     Recombine a secret, if enough shares are presented.
3219
3220                     Parameters
3221                            shares (tuples) -- At least k  tuples,  each  con‐
3222                            tainin  the  index  (an  integer) and the share (a
3223                            byte string, 16 bytes long) that were assigned  to
3224                            a participant.
3225
3226                     Returns
3227                            The  original  secret,  as a byte string (16 bytes
3228                            long).
3229
3230              static split(k, n, secret)
3231                     Split a secret into n shares.
3232
3233                     The secret can be reconstructed later when k  shares  out
3234                     of the original n are recombined. Each share must be kept
3235                     confidential to the person it was assigned to.
3236
3237                     Each share is associated to an index (starting  from  1),
3238                     which must be presented when the secret is recombined.
3239
3240                     Parameters
3241
3242                            · k (integer) -- The number of shares that must be
3243                              present in order to reconstruct the secret.
3244
3245                            · n (integer) -- The total  number  of  shares  to
3246                              create (larger than k).
3247
3248                            · secret (byte string) -- The 16 byte string (e.g.
3249                              the AES128 key) to split.
3250
3251                     Returns
3252                            n tuples, each containing  the  unique  index  (an
3253                            integer)  and  the  share (a byte string, 16 bytes
3254                            long) meant for a participant.
3255
3256       · kdf
3257
3258       · ss
3259
3260   Crypto.IO package
3261       Modules for reading and writing cryptographic data.
3262
3263       · pem
3264
3265       · pkcs8
3266
3267   PEM
3268       Set of functions for encapsulating data according to the PEM format.
3269
3270       PEM (Privacy Enhanced Mail) was an IETF standard  for  securing  emails
3271       via a Public Key Infrastructure. It is specified in RFC 1421-1424.
3272
3273       Even  though it has been abandoned, the simple message encapsulation it
3274       defined is still widely used today for  encoding  binary  cryptographic
3275       objects like keys and certificates into text.
3276
3277       Crypto.IO.PEM.encode(data, marker, passphrase=None, randfunc=None)
3278              Encode a piece of binary data into PEM format.
3279
3280              Parameters
3281
3282                     · data  (byte  string)  --  The  piece  of binary data to
3283                       encode.
3284
3285                     · marker (string) -- The marker for the PEM  block  (e.g.
3286                       "PUBLIC  KEY").   Note that there is no official master
3287                       list for all allowed markers.  Still, you can refer  to
3288                       the OpenSSL source code.
3289
3290                     · passphrase  (byte  string)  --  If given, the PEM block
3291                       will  be  encrypted.  The  key  is  derived  from   the
3292                       passphrase.
3293
3294                     · randfunc  (callable)  -- Random number generation func‐
3295                       tion; it accepts an integer N and returns a byte string
3296                       of  random  data, N bytes long. If not given, a new one
3297                       is instantiated.
3298
3299              Returns
3300                     The PEM block, as a string.
3301
3302       Crypto.IO.PEM.decode(pem_data, passphrase=None)
3303              Decode a PEM block into binary.
3304
3305              Parameters
3306
3307                     · pem_data (string) -- The PEM block.
3308
3309                     · passphrase (byte string) -- If given and the PEM  block
3310                       is   encrypted,  the  key  will  be  derived  from  the
3311                       passphrase.
3312
3313              Returns
3314                     A tuple with the binary data, the marker  string,  and  a
3315                     boolean to indicate if decryption was performed.
3316
3317              Raises ValueError  --  if  decoding  fails,  if  the PEM file is
3318                     encrypted and no passphrase has been provided or  if  the
3319                     passphrase is incorrect.
3320
3321   PKCS#8
3322       PKCS#8  is a standard for storing and transferring private key informa‐
3323       tion.  The wrapped key can either be clear or encrypted.
3324
3325       All encryption algorithms are based on passphrase-based key derivation.
3326       The following mechanisms are fully supported:
3327
3328       · PBKDF2WithHMAC-SHA1AndAES128-CBC
3329
3330       · PBKDF2WithHMAC-SHA1AndAES192-CBC
3331
3332       · PBKDF2WithHMAC-SHA1AndAES256-CBC
3333
3334       · PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC
3335
3336       · scryptAndAES128-CBC
3337
3338       · scryptAndAES192-CBC
3339
3340       · scryptAndAES256-CBC
3341
3342       The  following  mechanisms are only supported for importing keys.  They
3343       are much weaker than the ones listed above, and they are  provided  for
3344       backward compatibility only:
3345
3346       · pbeWithMD5AndRC2-CBC
3347
3348       · pbeWithMD5AndDES-CBC
3349
3350       · pbeWithSHA1AndRC2-CBC
3351
3352       · pbeWithSHA1AndDES-CBC
3353
3354       Crypto.IO.PKCS8.wrap(private_key,   key_oid,  passphrase=None,  protec‐
3355       tion=None, prot_params=None, key_params=None, randfunc=None)
3356              Wrap a private key into a PKCS#8 blob (clear or encrypted).
3357
3358              Parameters
3359
3360                     · private_key (byte string) -- The private key encoded in
3361                       binary form. The actual encoding is algorithm specific.
3362                       In most cases, it is DER.
3363
3364                     · key_oid (string) -- The object identifier (OID) of  the
3365                       private  key  to  wrap.   It  is  a dotted string, like
3366                       1.2.840.113549.1.1.1 (for RSA keys).
3367
3368                     · passphrase (bytes  string  or  string)  --  The  secret
3369                       passphrase from which the wrapping key is derived.  Set
3370                       it only if encryption is required.
3371
3372                     · protection (string) -- The identifier of the  algorithm
3373                       to  use  for  securely  wrapping  the key.  The default
3374                       value is PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC.
3375
3376                     · prot_params (dictionary) --
3377
3378                       Parameters for the protection algorithm.
3379
3380                           ┌────────────────┬────────────────────────────┐
3381                           │Key             │ Description                │
3382                           ├────────────────┼────────────────────────────┤
3383                           │iteration_count │ The   KDF   algorithm   is │
3384                           │                │ repeated  several times to │
3385                           │                │ slow  down   brute   force │
3386                           │                │ attacks    on    passwords │
3387                           │                │ (called  N  or  CPU/memory │
3388                           │                │ cost   in   scrypt).   The │
3389                           │                │ default value  for  PBKDF2 │
3390                           │                │ is   1000.    The  default │
3391                           │                │ value for scrypt is 16384. │
3392                           ├────────────────┼────────────────────────────┤
3393                           │salt_size       │ Salt  is  used  to  thwart │
3394                           │                │ dictionary   and   rainbow │
3395                           │                │ attacks on passwords.  The │
3396                           │                │ default value is 8 bytes.  │
3397                           ├────────────────┼────────────────────────────┤
3398                           │block_size      │ (scrypt  only) Memory-cost │
3399                           │                │ (r). The default value  is │
3400                           │                │ 8.                         │
3401                           ├────────────────┼────────────────────────────┤
3402                           │parallelization │ (scrypt   only)   CPU-cost │
3403                           │                │ (p). The default value  is │
3404                           │                │ 1.                         │
3405                           └────────────────┴────────────────────────────┘
3406
3407
3408                     · key_params  (DER  object)  --  The algorithm parameters
3409                       associated to the private  key.   It  is  required  for
3410                       algorithms like DSA, but not for others like RSA.
3411
3412                     · randfunc  (callable)  -- Random number generation func‐
3413                       tion; it should accept a single integer N and return  a
3414                       string of random data, N bytes long.  If not specified,
3415                       a new RNG will be instantiated from Crypto.Random.
3416
3417              Returns
3418                     The PKCS#8-wrapped private key (possibly encrypted), as a
3419                     byte string.
3420
3421       Crypto.IO.PKCS8.unwrap(p8_private_key, passphrase=None)
3422              Unwrap a private key from a PKCS#8 blob (clear or encrypted).
3423
3424              Parameters
3425
3426                     · p8_private_key (byte string) -- The private key wrapped
3427                       into a PKCS#8 blob, DER encoded.
3428
3429                     · passphrase (byte string or string) -- The passphrase to
3430                       use to decrypt the blob (if it is encrypted).
3431
3432              Returns
3433                     A tuple containing
3434
3435                        1. the  algorithm  identifier of the wrapped key (OID,
3436                           dotted string)
3437
3438                        2. the private key (byte string, DER encoded)
3439
3440                        3. the  associated  parameters   (byte   string,   DER
3441                           encoded) or None
3442
3443
3444              Raises ValueError -- if decoding fails
3445
3446   Crypto.Random package
3447       Crypto.Random.get_random_bytes(N)
3448              Return a random byte string of length N.
3449
3450   Crypto.Random.random module
3451       Crypto.Random.random.getrandbits(N)
3452              Return a random integer, at most N bits long.
3453
3454       Crypto.Random.random.randrange([start], stop[, step])
3455              Return  a  random  integer in the range (start, stop, step).  By
3456              default, start is 0 and step is 1.
3457
3458       Crypto.Random.random.randint(a, b)
3459              Return a random integer in the range no smaller than  a  and  no
3460              larger than b.
3461
3462       Crypto.Random.random.choice(seq)
3463              Return a random element picked from the sequence seq.
3464
3465       Crypto.Random.random.shuffle(seq)
3466              Randomly shuffle the sequence seq in-place.
3467
3468       Crypto.Random.random.sample(population, k)
3469              Randomly chooses k distinct elements from the list population.
3470
3471   Crypto.Util package
3472       Useful modules that don't belong in any other package.
3473
3474   Crypto.Util.asn1 module
3475       This  module  provides  minimal support for encoding and decoding ASN.1
3476       DER objects.
3477
3478       class       Crypto.Util.asn1.DerObject(asn1Id=None,        payload=b'',
3479       implicit=None, constructed=False, explicit=None)
3480              Base class for defining a single DER object.
3481
3482              This class should never be directly instantiated.
3483
3484              decode(der_encoded, strict=False)
3485                     Decode  a  complete  DER element, and re-initializes this
3486                     object with it.
3487
3488                     Parameters
3489                            der_encoded (byte string) -- A complete  DER  ele‐
3490                            ment.
3491
3492                     Raises ValueError -- in case of parsing errors.
3493
3494              encode()
3495                     Return  this  DER element, fully encoded as a binary byte
3496                     string.
3497
3498       class        Crypto.Util.asn1.DerInteger(value=0,        implicit=None,
3499       explicit=None)
3500              Class to model a DER INTEGER.
3501
3502              An example of encoding is:
3503
3504                 >>> from Crypto.Util.asn1 import DerInteger
3505                 >>> from binascii import hexlify, unhexlify
3506                 >>> int_der = DerInteger(9)
3507                 >>> print hexlify(int_der.encode())
3508
3509              which will show 020109, the DER encoding of 9.
3510
3511              And for decoding:
3512
3513                 >>> s = unhexlify(b'020109')
3514                 >>> try:
3515                 >>>   int_der = DerInteger()
3516                 >>>   int_der.decode(s)
3517                 >>>   print int_der.value
3518                 >>> except ValueError:
3519                 >>>   print "Not a valid DER INTEGER"
3520
3521              the output will be 9.
3522
3523              Variables
3524                     value (integer) -- The integer value
3525
3526              decode(der_encoded, strict=False)
3527                     Decode  a  complete  DER  INTEGER DER, and re-initializes
3528                     this object with it.
3529
3530                     Parameters
3531                            der_encoded (byte string) --  A  complete  INTEGER
3532                            DER element.
3533
3534                     Raises ValueError -- in case of parsing errors.
3535
3536              encode()
3537                     Return the DER INTEGER, fully encoded as a binary string.
3538
3539       class Crypto.Util.asn1.DerOctetString(value=b'', implicit=None)
3540              Class to model a DER OCTET STRING.
3541
3542              An example of encoding is:
3543
3544              >>> from Crypto.Util.asn1 import DerOctetString
3545              >>> from binascii import hexlify, unhexlify
3546              >>> os_der = DerOctetString(b'\xaa')
3547              >>> os_der.payload += b'\xbb'
3548              >>> print hexlify(os_der.encode())
3549
3550              which  will  show 0402aabb, the DER encoding for the byte string
3551              b'\xAA\xBB'.
3552
3553              For decoding:
3554
3555              >>> s = unhexlify(b'0402aabb')
3556              >>> try:
3557              >>>   os_der = DerOctetString()
3558              >>>   os_der.decode(s)
3559              >>>   print hexlify(os_der.payload)
3560              >>> except ValueError:
3561              >>>   print "Not a valid DER OCTET STRING"
3562
3563              the output will be aabb.
3564
3565              Variables
3566                     payload (byte string) -- The content of the string
3567
3568       class Crypto.Util.asn1.DerNull
3569              Class to model a DER NULL element.
3570
3571       class Crypto.Util.asn1.DerSequence(startSeq=None, implicit=None)
3572              Class to model a DER SEQUENCE.
3573
3574              This object behaves like a dynamic Python sequence.
3575
3576              Sub-elements that are INTEGERs behave like Python integers.
3577
3578              Any other sub-element is a binary string encoded as  a  complete
3579              DER sub-element (TLV).
3580
3581              An example of encoding is:
3582
3583              >>> from Crypto.Util.asn1 import DerSequence, DerInteger
3584              >>> from binascii import hexlify, unhexlify
3585              >>> obj_der = unhexlify('070102')
3586              >>> seq_der = DerSequence([4])
3587              >>> seq_der.append(9)
3588              >>> seq_der.append(obj_der.encode())
3589              >>> print hexlify(seq_der.encode())
3590
3591              which  will show 3009020104020109070102, the DER encoding of the
3592              sequence containing 4, 9, and the object with payload 02.
3593
3594              For decoding:
3595
3596              >>> s = unhexlify(b'3009020104020109070102')
3597              >>> try:
3598              >>>   seq_der = DerSequence()
3599              >>>   seq_der.decode(s)
3600              >>>   print len(seq_der)
3601              >>>   print seq_der[0]
3602              >>>   print seq_der[:]
3603              >>> except ValueError:
3604              >>>   print "Not a valid DER SEQUENCE"
3605
3606              the output will be:
3607
3608                 3
3609                 4
3610                 [4, 9, b'.....']
3611
3612              decode(der_encoded,       strict=False,        nr_elements=None,
3613              only_ints_expected=False)
3614                     Decode  a  complete DER SEQUENCE, and re-initializes this
3615                     object with it.
3616
3617                     Parameters
3618
3619                            · der_encoded (byte string) -- A complete SEQUENCE
3620                              DER element.
3621
3622                            · nr_elements  (None  or  integer or list of inte‐
3623                              gers) -- The number of members the SEQUENCE  can
3624                              have
3625
3626                            · only_ints_expected   (boolean)  --  Whether  the
3627                              SEQUENCE is expected to contain only integers.
3628
3629                            · strict (boolean) -- Whether decoding must  check
3630                              for strict DER compliancy.
3631
3632                     Raises ValueError -- in case of parsing errors.
3633
3634                     DER  INTEGERs are decoded into Python integers. Any other
3635                     DER element is not decoded. Its validity is not checked.
3636
3637              encode()
3638                     Return this DER  SEQUENCE,  fully  encoded  as  a  binary
3639                     string.
3640
3641                     Raises ValueError -- if some elements in the sequence are
3642                            neither integers nor byte strings.
3643
3644              hasInts(only_non_negative=True)
3645                     Return the number of items  in  this  sequence  that  are
3646                     integers.
3647
3648                     Parameters
3649                            only_non_negative  (boolean)  -- If True, negative
3650                            integers are not counted in.
3651
3652              hasOnlyInts(only_non_negative=True)
3653                     Return True if all items in this sequence are integers or
3654                     non-negative integers.
3655
3656                     This  function returns False is the sequence is empty, or
3657                     at least one member is not an integer.
3658
3659                     Parameters
3660                            only_non_negative (boolean) -- If True, the  pres‐
3661                            ence  of  negative  integers  causes the method to
3662                            return False.
3663
3664       class       Crypto.Util.asn1.DerObjectId(value='',       implicit=None,
3665       explicit=None)
3666              Class to model a DER OBJECT ID.
3667
3668              An example of encoding is:
3669
3670              >>> from Crypto.Util.asn1 import DerObjectId
3671              >>> from binascii import hexlify, unhexlify
3672              >>> oid_der = DerObjectId("1.2")
3673              >>> oid_der.value += ".840.113549.1.1.1"
3674              >>> print hexlify(oid_der.encode())
3675
3676              which will show 06092a864886f70d010101, the DER encoding for the
3677              RSA Object Identifier 1.2.840.113549.1.1.1.
3678
3679              For decoding:
3680
3681              >>> s = unhexlify(b'06092a864886f70d010101')
3682              >>> try:
3683              >>>   oid_der = DerObjectId()
3684              >>>   oid_der.decode(s)
3685              >>>   print oid_der.value
3686              >>> except ValueError:
3687              >>>   print "Not a valid DER OBJECT ID"
3688
3689              the output will be 1.2.840.113549.1.1.1.
3690
3691              Variables
3692                     value (string) -- The Object ID (OID),  a  dot  separated
3693                     list of integers
3694
3695              decode(der_encoded, strict=False)
3696                     Decode  a complete DER OBJECT ID, and re-initializes this
3697                     object with it.
3698
3699                     Parameters
3700
3701                            · der_encoded (byte  string)  --  A  complete  DER
3702                              OBJECT ID.
3703
3704                            · strict  (boolean) -- Whether decoding must check
3705                              for strict DER compliancy.
3706
3707                     Raises ValueError -- in case of parsing errors.
3708
3709              encode()
3710                     Return the DER OBJECT  ID,  fully  encoded  as  a  binary
3711                     string.
3712
3713       class      Crypto.Util.asn1.DerBitString(value=b'',      implicit=None,
3714       explicit=None)
3715              Class to model a DER BIT STRING.
3716
3717              An example of encoding is:
3718
3719              >>> from Crypto.Util.asn1 import DerBitString
3720              >>> from binascii import hexlify, unhexlify
3721              >>> bs_der = DerBitString(b'\xaa')
3722              >>> bs_der.value += b'\xbb'
3723              >>> print hexlify(bs_der.encode())
3724
3725              which will show 040300aabb, the DER encoding for the bit  string
3726              b'\xAA\xBB'.
3727
3728              For decoding:
3729
3730              >>> s = unhexlify(b'040300aabb')
3731              >>> try:
3732              >>>   bs_der = DerBitString()
3733              >>>   bs_der.decode(s)
3734              >>>   print hexlify(bs_der.value)
3735              >>> except ValueError:
3736              >>>   print "Not a valid DER BIT STRING"
3737
3738              the output will be aabb.
3739
3740              Variables
3741                     value (byte string) -- The content of the string
3742
3743              decode(der_encoded, strict=False)
3744                     Decode a complete DER BIT STRING, and re-initializes this
3745                     object with it.
3746
3747                     Parameters
3748
3749                            · der_encoded (byte string) -- a complete DER  BIT
3750                              STRING.
3751
3752                            · strict  (boolean) -- Whether decoding must check
3753                              for strict DER compliancy.
3754
3755                     Raises ValueError -- in case of parsing errors.
3756
3757              encode()
3758                     Return the DER BIT STRING,  fully  encoded  as  a  binary
3759                     string.
3760
3761       class Crypto.Util.asn1.DerSetOf(startSet=None, implicit=None)
3762              Class to model a DER SET OF.
3763
3764              An example of encoding is:
3765
3766              >>> from Crypto.Util.asn1 import DerBitString
3767              >>> from binascii import hexlify, unhexlify
3768              >>> so_der = DerSetOf([4,5])
3769              >>> so_der.add(6)
3770              >>> print hexlify(so_der.encode())
3771
3772              which  will  show  3109020104020105020106, the DER encoding of a
3773              SET OF with items 4,5, and 6.
3774
3775              For decoding:
3776
3777              >>> s = unhexlify(b'3109020104020105020106')
3778              >>> try:
3779              >>>   so_der = DerSetOf()
3780              >>>   so_der.decode(s)
3781              >>>   print [x for x in so_der]
3782              >>> except ValueError:
3783              >>>   print "Not a valid DER SET OF"
3784
3785              the output will be [4, 5, 6].
3786
3787              add(elem)
3788                     Add an element to the set.
3789
3790                     Parameters
3791                            elem (byte string or integer) -- An element of the
3792                            same  type  of objects already in the set.  It can
3793                            be an integer or a DER encoded object.
3794
3795              decode(der_encoded, strict=False)
3796                     Decode a complete SET OF DER element, and  re-initializes
3797                     this object with it.
3798
3799                     DER  INTEGERs are decoded into Python integers. Any other
3800                     DER element  is  left  undecoded;  its  validity  is  not
3801                     checked.
3802
3803                     Parameters
3804
3805                            · der_encoded  (byte string) -- a complete DER BIT
3806                              SET OF.
3807
3808                            · strict (boolean) -- Whether decoding must  check
3809                              for strict DER compliancy.
3810
3811                     Raises ValueError -- in case of parsing errors.
3812
3813              encode()
3814                     Return this SET OF DER element, fully encoded as a binary
3815                     string.
3816
3817   Crypto.Util.Padding module
3818       This module provides minimal support for adding and  removing  standard
3819       padding from data. Example:
3820
3821          >>> from Crypto.Util.Padding import pad, unpad
3822          >>> from Crypto.Cipher import AES
3823          >>> from Crypto.Random import get_random_bytes
3824          >>>
3825          >>> data = b'Unaligned'   # 9 bytes
3826          >>> key = get_random_bytes(32)
3827          >>> iv = get_random_bytes(16)
3828          >>>
3829          >>> cipher1 = AES.new(key, AES.MODE_CBC, iv)
3830          >>> ct = cipher1.encrypt(pad(data, 16))
3831          >>>
3832          >>> cipher2 = AES.new(key, AES.MODE_CBC, iv)
3833          >>> pt = unpad(cipher2.decrypt(ct), 16)
3834          >>> assert(data == pt)
3835
3836       Crypto.Util.Padding.pad(data_to_pad, block_size, style='pkcs7')
3837              Apply standard padding.
3838
3839              Parameters
3840
3841                     · data_to_pad  (byte string) -- The data that needs to be
3842                       padded.
3843
3844                     · block_size (integer) -- The block boundary to  use  for
3845                       padding. The output length is guaranteed to be a multi‐
3846                       ple of block_size.
3847
3848                     · style (string) -- Padding algorithm. It can be  'pkcs7'
3849                       (default), 'iso7816' or 'x923'.
3850
3851              Returns
3852                     the  original  data with the appropriate padding added at
3853                     the end.
3854
3855              Return type
3856                     byte string
3857
3858       Crypto.Util.Padding.unpad(padded_data, block_size, style='pkcs7')
3859              Remove standard padding.
3860
3861              Parameters
3862
3863                     · padded_data (byte string) -- A piece of data with  pad‐
3864                       ding that needs to be stripped.
3865
3866                     · block_size  (integer)  -- The block boundary to use for
3867                       padding.  The  input  length  must  be  a  multiple  of
3868                       block_size.
3869
3870                     · style  (string) -- Padding algorithm. It can be 'pkcs7'
3871                       (default), 'iso7816' or 'x923'.
3872
3873              Returns
3874                     data without padding.
3875
3876              Return type
3877                     byte string
3878
3879              Raises ValueError -- if the padding is incorrect.
3880
3881   Crypto.Util.RFC1751 module
3882       Crypto.Util.RFC1751.english_to_key(s)
3883              Transform a string into a corresponding key.
3884
3885              Example:
3886
3887                 >>> from Crypto.Util.RFC1751 import english_to_key
3888                 >>> english_to_key('RAM LOIS GOAD CREW CARE HIT')
3889                 b'66666666'
3890
3891              Parameters
3892                     s (string) -- the string  with  the  words  separated  by
3893                     whitespace; the number of words must be a multiple of 6.
3894
3895              Returns
3896                     A byte string.
3897
3898       Crypto.Util.RFC1751.key_to_english(key)
3899              Transform  an  arbitrary  key  into  a string containing English
3900              words.
3901
3902              Example:
3903
3904                 >>> from Crypto.Util.RFC1751 import key_to_english
3905                 >>> key_to_english(b'66666666')
3906                 'RAM LOIS GOAD CREW CARE HIT'
3907
3908              Parameters
3909                     key (byte string) -- The key to convert. Its length  must
3910                     be a multiple of 8.
3911
3912              Returns
3913                     A string of English words.
3914
3915   Crypto.Util.strxor module
3916       Fast XOR for byte strings.
3917
3918       Crypto.Util.strxor.strxor(term1, term2, output=None)
3919              XOR two byte strings.
3920
3921              Parameters
3922
3923                     · term1 (bytes/bytearray/memoryview) -- The first term of
3924                       the XOR operation.
3925
3926                     · term2 (bytes/bytearray/memoryview) -- The  second  term
3927                       of the XOR operation.
3928
3929                     · output (bytearray/memoryview) -- The location where the
3930                       result must be written to.   If  None,  the  result  is
3931                       returned.
3932
3933              Return If  output  is  None, a new bytes string with the result.
3934                     Otherwise None.
3935
3936       Crypto.Util.strxor.strxor_c(term, c, output=None)
3937              XOR a byte string with a repeated sequence of characters.
3938
3939              Parameters
3940
3941                     · term (bytes/bytearray/memoryview) -- The first term  of
3942                       the XOR operation.
3943
3944                     · c  (bytes) -- The byte that makes up the second term of
3945                       the XOR operation.
3946
3947                     · output (None or bytearray/memoryview) -- If  not  None,
3948                       the location where the result is stored into.
3949
3950              Returns
3951                     If  output  is  None, a new bytes string with the result.
3952                     Otherwise None.
3953
3954   Crypto.Util.Counter module
3955       Richer counter functions for CTR cipher mode.
3956
3957       CTR is a mode of operation for block ciphers.
3958
3959       The plaintext is broken up in blocks and each block is  XOR-ed  with  a
3960       keystream  to  obtain the ciphertext.  The keystream is produced by the
3961       encryption of a sequence of counter blocks, which all need to  be  dif‐
3962       ferent to avoid repetitions in the keystream. Counter blocks don't need
3963       to be secret.
3964
3965       The most straightforward approach is to include a  counter  field,  and
3966       increment it by one within each subsequent counter block.
3967
3968       The new() function at the module level under Crypto.Cipher instantiates
3969       a new CTR cipher object for the relevant base algorithm.   Its  parame‐
3970       ters allow you define a counter block with a fixed structure:
3971
3972       · an optional, fixed prefix
3973
3974       · the counter field encoded in big endian mode
3975
3976       The length of the two components can vary, but together they must be as
3977       large as the block size (e.g. 16 bytes for AES).
3978
3979       Alternatively, the counter parameter can be  used  to  pass  a  counter
3980       block    object    (created    in    advance    with    the    function
3981       Crypto.Util.Counter.new()) for a more complex composition:
3982
3983       · an optional, fixed prefix
3984
3985       · the counter field, encoded in big endian or little endian mode
3986
3987       · an optional, fixed suffix
3988
3989       As before, the total length must match the block size.
3990
3991       The counter blocks with a big endian counter will look like this:
3992         [image]
3993
3994       The counter blocks with a little endian counter will look like this:
3995         [image]
3996
3997       Example of AES-CTR encryption with custom counter:
3998
3999          from Crypto.Cipher import AES
4000          from Crypto.Util import Counter
4001          from Crypto import Random
4002
4003          nonce = Random.get_random_bytes(4)
4004          ctr = Counter.new(64, prefix=nonce, suffix=b'ABCD', little_endian=True, initial_value=10)
4005          key = b'AES-128 symm key'
4006          plaintext = b'X'*1000000
4007          cipher = AES.new(key, AES.MODE_CTR, counter=ctr)
4008          ciphertext = cipher.encrypt(plaintext)
4009
4010       Crypto.Util.Counter.new(nbits, prefix=b'', suffix=b'', initial_value=1,
4011       little_endian=False, allow_wraparound=False)
4012              Create  a  stateful  counter  block  function  suitable  for CTR
4013              encryption modes.
4014
4015              Each call to the function returns the next counter block.   Each
4016              counter block is made up by three parts:
4017
4018                             ┌───────┬───────────────┬─────────┐
4019                             │prefix │ counter value │ postfix │
4020                             └───────┴───────────────┴─────────┘
4021
4022              The counter value is incremented by 1 at each call.
4023
4024              Parameters
4025
4026                     · nbits (integer) -- Length of the desired counter value,
4027                       in bits. It must be a multiple of 8.
4028
4029                     · prefix (byte string) --  The  constant  prefix  of  the
4030                       counter block. By default, no prefix is used.
4031
4032                     · suffix  (byte  string)  --  The constant postfix of the
4033                       counter block. By default, no suffix is used.
4034
4035                     · initial_value (integer) -- The  initial  value  of  the
4036                       counter. Default value is 1.
4037
4038                     · little_endian  (boolean) -- If True, the counter number
4039                       will be encoded in  little  endian  format.   If  False
4040                       (default), in big endian format.
4041
4042                     · allow_wraparound   (boolean)   --   This  parameter  is
4043                       ignored.
4044
4045              Returns
4046                     An object that can be passed with the  counter  parameter
4047                     to a CTR mode cipher.
4048
4049              It  must  hold that len(prefix) + nbits//8 + len(suffix) matches
4050              the block size of the underlying block cipher.
4051
4052   Crypto.Util.number module
4053       Crypto.Util.number.GCD(x, y)
4054              Greatest Common Denominator of x and y.
4055
4056       Crypto.Util.number.bytes_to_long(s)
4057              Convert a byte string to a long integer (big endian).
4058
4059              In Python 3.2+, use the native method instead:
4060
4061                 >>> int.from_bytes(s, 'big')
4062
4063              For instance:
4064
4065                 >>> int.from_bytes(b'P', 'big')
4066                 80
4067
4068              This is (essentially) the inverse of long_to_bytes().
4069
4070       Crypto.Util.number.ceil_div(n, d)
4071              Return ceil(n/d), that is, the smallest integer r such that  r*d
4072              >= n
4073
4074       Crypto.Util.number.getPrime(N, randfunc=None)
4075              Return a random N-bit prime number.
4076
4077              If randfunc is omitted, then Random.get_random_bytes() is used.
4078
4079       Crypto.Util.number.getRandomInteger(N, randfunc=None)
4080              Return a random number at most N bits long.
4081
4082              If randfunc is omitted, then Random.get_random_bytes() is used.
4083
4084              Deprecated  since version 3.0: This function is for internal use
4085              only  and  may  be  renamed  or  removed  in  the  future.   Use
4086              Crypto.Random.random.getrandbits() instead.
4087
4088
4089       Crypto.Util.number.getRandomNBitInteger(N, randfunc=None)
4090              Return a random number with exactly N-bits, i.e. a random number
4091              between 2**(N-1) and (2**N)-1.
4092
4093              If randfunc is omitted, then Random.get_random_bytes() is used.
4094
4095              Deprecated since version 3.0: This function is for internal  use
4096              only and may be renamed or removed in the future.
4097
4098
4099       Crypto.Util.number.getRandomRange(a, b, randfunc=None)
4100              Return a random number n so that a <= n < b.
4101
4102              If randfunc is omitted, then Random.get_random_bytes() is used.
4103
4104              Deprecated  since version 3.0: This function is for internal use
4105              only  and  may  be  renamed  or  removed  in  the  future.   Use
4106              Crypto.Random.random.randrange() instead.
4107
4108
4109       Crypto.Util.number.getStrongPrime(N,   e=0,  false_positive_prob=1e-06,
4110       randfunc=None)
4111              Return a random strong N-bit prime number.  In this  context,  p
4112              is  a  strong prime if p-1 and p+1 have at least one large prime
4113              factor.
4114
4115              Parameters
4116
4117                     · N (integer) -- the exact length of  the  strong  prime.
4118                       It must be a multiple of 128 and > 512.
4119
4120                     · e  (integer)  -- if provided, the returned prime (minus
4121                       1) will be coprime to e and thus suitable for RSA where
4122                       e is the public exponent.
4123
4124                     · false_positive_prob  (float)  -- The statistical proba‐
4125                       bility for the result not to be actually  a  prime.  It
4126                       defaults  to 10-6.  Note that the real probability of a
4127                       false-positive is far less. This is just the mathemati‐
4128                       cally provable limit.
4129
4130                     · randfunc  (callable) -- A function that takes a parame‐
4131                       ter N and that returns a random  byte  string  of  such
4132                       length.   If  omitted, Crypto.Random.get_random_bytes()
4133                       is used.
4134
4135              Returns
4136                     The new strong prime.
4137
4138              Deprecated since version 3.0: This function is for internal  use
4139              only and may be renamed or removed in the future.
4140
4141
4142       Crypto.Util.number.inverse(u, v)
4143              The inverse of u mod v.
4144
4145       Crypto.Util.number.isPrime(N, false_positive_prob=1e-06, randfunc=None)
4146              Test if a number N is a prime.
4147
4148              Parameters
4149
4150                     · false_positive_prob  (float)  -- The statistical proba‐
4151                       bility for the result not to be actually  a  prime.  It
4152                       defaults  to 10-6.  Note that the real probability of a
4153                       false-positive is far less.  This is just the mathemat‐
4154                       ically provable limit.
4155
4156                     · randfunc  (callable) -- A function that takes a parame‐
4157                       ter N and that returns a random  byte  string  of  such
4158                       length.   If  omitted, Crypto.Random.get_random_bytes()
4159                       is used.
4160
4161              Returns
4162                     True is the input is indeed prime.
4163
4164       Crypto.Util.number.long_to_bytes(n, blocksize=0)
4165              Convert an integer to a byte string.
4166
4167              In Python 3.2+, use the native method instead:
4168
4169                 >>> n.to_bytes(blocksize, 'big')
4170
4171              For instance:
4172
4173                 >>> n = 80
4174                 >>> n.to_bytes(2, 'big')
4175                 b'P'
4176
4177              If the optional blocksize is provided and greater than zero, the
4178              byte  string  is padded with binary zeros (on the front) so that
4179              the total length of the output is a multiple of blocksize.
4180
4181              If blocksize is zero or not provided, the byte string will be of
4182              minimal length.
4183
4184       Crypto.Util.number.size(N)
4185              Returns the size of the number N in bits.
4186
4187       All  cryptographic  functionalities are organized in sub-packages; each
4188       sub-package is dedicated to solving a specific class of problems.
4189
4190                   ┌─────────────────┬────────────────────────────┐
4191                   │Package          │ Description                │
4192                   ├─────────────────┼────────────────────────────┤
4193                   │Crypto.Cipher    │ Modules   for   protecting │
4194                   │                 │ confidentiality  that  is, │
4195                   │                 │ for     encrypting     and │
4196                   │                 │ decrypting  data (example: │
4197                   │                 │ AES).                      │
4198                   ├─────────────────┼────────────────────────────┤
4199                   │Crypto.Signature │ Modules    for    assuring │
4200                   │                 │ authenticity, that is, for │
4201                   │                 │ creating   and   verifying │
4202                   │                 │ digital signatures of mes‐ │
4203                   │                 │ sages   (example:   PKCS#1 │
4204                   │                 │ v1.5).                     │
4205                   ├─────────────────┼────────────────────────────┤
4206                   │Crypto.Hash      │ Modules for creating cryp‐ │
4207                   │                 │ tographic  digests  (exam‐ │
4208                   │                 │ ple: SHA-256).             │
4209                   ├─────────────────┼────────────────────────────┤
4210                   │Crypto.PublicKey │ Modules   for  generating, │
4211                   │                 │ exporting   or   importing │
4212                   │                 │ public  keys (example: RSA │
4213                   │                 │ or ECC).                   │
4214                   └─────────────────┴────────────────────────────┘
4215
4216
4217
4218
4219                   │Crypto.Protocol  │ Modules   for   faciliting │
4220                   │                 │ secure      communications │
4221                   │                 │ between parties,  in  most │
4222                   │                 │ cases  by leveraging cryp‐ │
4223                   │                 │ tograpic  primitives  from │
4224                   │                 │ other   modules  (example: │
4225                   │                 │ Shamir's  Secret   Sharing │
4226                   │                 │ scheme).                   │
4227                   ├─────────────────┼────────────────────────────┤
4228                   │Crypto.IO        │ Modules  for  dealing with │
4229                   │                 │ encodings  commonly   used │
4230                   │                 │ for   cryptographic   data │
4231                   │                 │ (example: PEM).            │
4232                   ├─────────────────┼────────────────────────────┤
4233                   │Crypto.Random    │ Modules   for   generating │
4234                   │                 │ random data.               │
4235                   ├─────────────────┼────────────────────────────┤
4236                   │Crypto.Util      │ General  purpose  routines │
4237                   │                 │ (example:  XOR  for   byte │
4238                   │                 │ strings).                  │
4239                   └─────────────────┴────────────────────────────┘
4240
4241       In  certain cases, there is some overlap between these categories.  For
4242       instance, authenticity  is  also  provided  by  Message  Authentication
4243       Codes, and some can be built using digests, so they are included in the
4244       Crypto.Hash package (example: HMAC).  Also,  cryptographers  have  over
4245       time  realized  that encryption without authentication is often of lim‐
4246       ited value so recent ciphers found in the Crypto.Cipher  package  embed
4247       it (example: GCM).
4248
4249       PyCryptodome strives to maintain strong backward compatibility with the
4250       old PyCrypto's API (except for those few cases where that is harmful to
4251       security) so a few modules don't appear where they should (example: the
4252       ASN.1 module is under Crypto.Util as opposed to Crypto.IO).
4253

EXAMPLES

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

FREQUENTLY ASKED QUESTIONS

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

CONTRIBUTE AND SUPPORT

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

FUTURE PLANS

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

CHANGELOG

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

LICENSE

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

AUTHOR

5465       Legrandin
5466
5468       2017, Helder Eijs
5469
5470
5471
5472
54733.8                              Apr 06, 2019                  PYCRYPTODOME(1)
Impressum