ECC¶
ECC (Elliptic Curve Cryptography) is a modern and efficient type of public key cryptography. Its security is based on the difficulty to solve discrete logarithms on the field defined by specific equations computed over a curve.
ECC can be used to create digital signatures or to perform a key exchange.
Compared to traditional algorithms like RSA, an ECC key is significantly smaller at the same security level. For instance, a 3072-bit RSA key takes 768 bytes whereas the equally strong NIST P-256 private key only takes 32 bytes (that is, 256 bits).
With this module you can generate new ECC keys:
>>> from Crypto.PublicKey import ECC
>>>
>>> mykey = ECC.generate(curve='p256')
export an ECC private key and protect it with a password, so that it is resistant to brute force attacks:
>>> pwd = b'secret'
>>> with open("myprivatekey.pem", "wt") as f:
... data = mykey.export_key(format='PEM', passphrase=pwd)
... f.write(data)
and reimport it later:
>>> pwd = b'secret'
>>> with open("myprivatekey.pem", "rt") as f:
... data = f.read()
... mykey = ECC.import_key(data, pwd)
The key is encrypted with PKCS#8 and 'PBKDF2WithHMAC-SHA256AndAES256-CBC'
by default. To choose another scheme, pass the protection and prot_params
parameters (see the encryption parameters of PKCS#8).
You can also export the public key, which is not sensitive:
>>> with open("mypublickey.pem", "wt") as f:
... data = mykey.public_key().export_key(format='PEM')
Curve |
Canonical name |
Aliases |
|---|---|---|
NIST P-192 |
|
|
NIST P-224 |
|
|
NIST P-256 |
|
|
NIST P-384 |
|
|
NIST P-521 |
|
|
Ed25519 |
|
|
Ed448 |
|
|
Curve25519 |
|
|
Curve448 |
|
|
For more information about each NIST curve see FIPS 186-4, Section D.1.2.
Curves Ed25519 and Ed448 are defined in RFC8032.
Curves Curve25519 and Curve448 are defined in RFC7748.
The ECC keys can be used to perform or verify signatures, using the modules
Crypto.Signature.DSS (ECDSA; NIST curves only)
or Crypto.Signature.eddsa (EdDSA; Ed25519 and Ed448 curve only).
- class Crypto.PublicKey.ECC.ConstructParams¶
- class Crypto.PublicKey.ECC.EccKey(*, curve=None, d=None, seed=None, point=None)¶
Class defining an ECC key. Do not instantiate directly. Use
generate(),construct()orimport_key()instead.- Variables:
curve (string) – The canonical name of the curve as defined in the ECC table.
pointQ (
EccPointorEccXPoint) – an ECC point representing the public component.d (integer) – A scalar that represents the private component in NIST P curves. It is smaller than the order of the generator point.
seed (bytes) – A seed that represents the private component in Ed22519 (32 bytes), Curve25519 (32 bytes), Curve448 (56 bytes), Ed448 (57 bytes).
- export_key(*, format, passphrase=None, use_pkcs8=True, protection=None, compress=False, prot_params=None, randfunc=None, threads=1)¶
Export this ECC key.
- Parameters:
format (string) –
The output format:
'DER'. The key will be encoded in ASN.1 DER format (binary). For a public key, the ASN.1subjectPublicKeyInfostructure defined in RFC5480 will be used. For a private key, the ASN.1ECPrivateKeystructure defined in RFC5915 is used instead (possibly within a PKCS#8 envelope, see theuse_pkcs8flag below).'PEM'. The key will be encoded in a PEM envelope (ASCII).'OpenSSH'. The key will be encoded in the OpenSSH format (ASCII, public keys only).'SEC1'. The public key (i.e., the EC point) will be encoded intobytesaccording to Section 2.3.3 of SEC1 (which is a subset of the older X9.62 ITU standard). Only for NIST P-curves.'raw'. The public key will be encoded asbytes, without any metadata.
passphrase (bytes or string) – (Private keys only) The passphrase to protect the private key.
use_pkcs8 (boolean) –
(Private keys only) If
True(default and recommended), the PKCS#8 representation will be used. It must beTruefor Ed25519, Ed448, Curve25519, and Curve448.If
Falseand a passphrase is present, the obsolete PEM encryption will be used. It derives the key with a single round of MD5, and is therefore easy to brute force: use it only with a high-entropy passphrase (like 16 random bytes), for compatibility with old software.protection (string) – The encryption scheme used when a private key is exported with password-protection and PKCS#8 (both
DERandPEMformats). For all possible protection schemes, refer to the encryption parameters of PKCS#8. The default is'PBKDF2WithHMAC-SHA256AndAES256-CBC'.compress (boolean) –
If
True, the method returns a more compact representation of the public key, with the X-coordinate only.If
False(default), the method returns the full public key.This parameter is ignored for Ed25519/Ed448/Curve25519/Curve448, as compression is mandatory.
prot_params (dict) – When a private key is exported with password-protection and PKCS#8 (both
DERandPEMformats), this dictionary contains the parameters to use to derive the encryption key from the passphrase. For all possible values, refer to the encryption parameters of PKCS#8. The defaults meet the OWASP recommendations (with the defaultprotection): there is no need to set them.randfunc (callable) – (Private keys only) A function that returns random bytes, for the encryption (salt and IV). By default,
Crypto.Random.get_random_bytes().threads (integer) – (Private keys only) The maximum number of threads used to derive the encryption key with scrypt (default: 1, no extra threads; 0 for all CPU cores). Only useful with PKCS#8, a scrypt
protectionand aparallelizationlarger than 1 inprot_params. The output does not depend on the number of threads.
Warning
If you don’t provide a passphrase, the private key will be exported in the clear!
- has_private()¶
Trueif this key can be used for making signatures or decrypting data.- Return type:
- exception Crypto.PublicKey.ECC.UnsupportedEccFeature¶
- Crypto.PublicKey.ECC.construct(**kwargs)¶
Build a new ECC key (private or public) starting from some base components.
In most cases, you will already have an existing key which you can read in with
import_key()instead of this function.- Parameters:
curve (string) – Mandatory. The name of the elliptic curve, as defined in the ECC table.
d (integer) – Mandatory for a private key and a NIST P-curve (e.g., P-256). It must be an integer in the range
[1..order-1].seed (bytes) – Mandatory for a private key and curves Ed25519 (32 bytes), Curve25519 (32 bytes), Curve448 (56 bytes) and Ed448 (57 bytes).
point_x (integer) – The X coordinate (affine) of the ECC point. Mandatory for a public key.
point_y (integer) – The Y coordinate (affine) of the ECC point. Mandatory for a public key, except for Curve25519 and Curve448.
- Returns:
a new ECC key object
- Return type:
- Crypto.PublicKey.ECC.generate(*, curve, randfunc=None)¶
Generate a new private key on the given curve.
- Parameters:
curve (string) – Mandatory. It must be a curve name defined in the ECC table.
randfunc (callable) – Optional. The RNG to read randomness from. If
None,Crypto.Random.get_random_bytes()is used.
- Return type:
- Crypto.PublicKey.ECC.import_key(encoded, passphrase=None, curve_name=None, *, max_iteration_count=None, threads=1, max_memory=None)¶
Import an ECC key (public or private).
- Parameters:
encoded (bytes or multi-line string) –
The ECC key to import. The function will try to automatically detect the right format.
Supported formats for an ECC public key:
X.509 certificate: binary (DER) or ASCII (PEM).
X.509
subjectPublicKeyInfo: binary (DER) or ASCII (PEM).SEC1 (or X9.62), as
bytes. NIST P curves only. You must also provide thecurve_name(with a value from the ECC table)OpenSSH line, defined in RFC5656 and RFC8709 (ASCII). This is normally the content of files like
~/.ssh/id_ecdsa.pub.
Supported formats for an ECC private key:
A binary
ECPrivateKeystructure, as defined in RFC5915 (DER). NIST P curves only.A PKCS#8 structure (or the more recent Asymmetric Key Package, RFC5958): binary (DER) or ASCII (PEM).
OpenSSH 6.5 and newer versions (ASCII).
Private keys can be in the clear or password-protected.
passphrase (byte string) – The passphrase to use for decrypting a private key. Encryption may be applied protected at the PEM level (not recommended) or at the PKCS#8 level (recommended). This parameter is ignored if the key in input is not encrypted.
curve_name (string) – For a SEC1 encoding only. This is the name of the curve, as defined in the ECC table.
max_iteration_count (integer) – The maximum value allowed for the PBKDF2 iteration count or the scrypt cost N·r·p/8 (that is, N for the usual r=8 and p=1) of a PKCS#8 encrypted key, or for the number of rounds of bcrypt_pbkdf of an encrypted OpenSSH key. A malicious key could require an extremely high number of iterations, tying up the CPU for hours. The default value is None: a limit for each KDF, which keeps the key derivation to about one minute at most (see the limits for decryption). Set it to
0to disable the check.threads (integer) – The maximum number of threads used to derive the decryption key with scrypt (default: 1, no extra threads; 0 for all CPU cores). Only a PKCS#8 key protected with scrypt and a parallelization parameter larger than 1 can use them.
max_memory (integer) – The maximum memory (in bytes) for the key derivation of a PKCS#8 encrypted key, as a limit on the total of all threads together (not on each thread). Only scrypt uses a significant amount: 128 · (N + 2) · r bytes for each thread, plus 256 · r · p bytes for all the flows together. If the requested threads do not fit, fewer are used (down to one); if a single thread does not fit, the key is rejected. The default value is None (a limit of 256 MiB). Set it to
0to disable the check.
Note
To import EdDSA private and public keys, when encoded as raw
bytes, use:Note
To import X25519/X448 private and public keys, when encoded as raw
bytes, use:- Returns:
a new ECC key object
- Return type:
- Raises:
PassphraseRequiredError – (a
ValueError) when the private key is encrypted, but no passphrase was provided.IncorrectPassphraseError – (a
ValueError) when the private key cannot be decrypted with the passphrase (most likely, the passphrase is wrong).UnsupportedEccFeature – (a
ValueError) when the key uses a curve or a feature that is not supported.ValueError – when the given key cannot be parsed.