Danger
This is a “Hazardous Materials” module. You should ONLY use it if you’re 100% absolutely sure that you know what you’re doing because this module is full of land mines, dragons, and dinosaurs with laser guns.
Elliptic curve cryptography
- cryptography.hazmat.primitives.asymmetric.ec.generate_private_key(curve)
New in version 0.5.
Generate a new private key on
curve
.- Parameters:
curve – An instance of
EllipticCurve
.- Returns:
A new instance of
EllipticCurvePrivateKey
.
- cryptography.hazmat.primitives.asymmetric.ec.derive_private_key(private_value, curve)[source]
New in version 1.6.
Derive a private key from
private_value
oncurve
.- Parameters:
private_value (int) – The secret scalar value.
curve – An instance of
EllipticCurve
.
- Returns:
A new instance of
EllipticCurvePrivateKey
.
Elliptic Curve Signature Algorithms
- class cryptography.hazmat.primitives.asymmetric.ec.ECDSA(algorithm)[source]
New in version 0.5.
The ECDSA signature algorithm first standardized in NIST publication FIPS 186-3, and later in FIPS 186-4.
Note that while elliptic curve keys can be used for both signing and key exchange, this is bad cryptographic practice. Instead, users should generate separate signing and ECDH keys.
- Parameters:
algorithm – An instance of
HashAlgorithm
.deterministic_signing (bool) –
A boolean flag defaulting to
False
that specifies whether the signing procedure should be deterministic or not, as defined in RFC 6979. This only impacts the signing process, verification is not affected (the verification process is the same for both deterministic and non-deterministic signed messages).New in version 43.0.0.
- Raises:
cryptography.exceptions.UnsupportedAlgorithm – If
deterministic_signing
is set toTrue
and the version of OpenSSL does not support ECDSA with deterministic signing.
>>> from cryptography.hazmat.primitives import hashes >>> from cryptography.hazmat.primitives.asymmetric import ec >>> private_key = ec.generate_private_key( ... ec.SECP384R1() ... ) >>> data = b"this is some data I'd like to sign" >>> signature = private_key.sign( ... data, ... ec.ECDSA(hashes.SHA256()) ... )
The
signature
is abytes
object, whose contents are DER encoded as described in RFC 3279. This can be decoded usingdecode_dss_signature()
.If your data is too large to be passed in a single call, you can hash it separately and pass that value using
Prehashed
.>>> from cryptography.hazmat.primitives.asymmetric import utils >>> chosen_hash = hashes.SHA256() >>> hasher = hashes.Hash(chosen_hash) >>> hasher.update(b"data & ") >>> hasher.update(b"more data") >>> digest = hasher.finalize() >>> sig = private_key.sign( ... digest, ... ec.ECDSA(utils.Prehashed(chosen_hash)) ... )
Verification requires the public key, the DER-encoded signature itself, the signed data, and knowledge of the hashing algorithm that was used when producing the signature:
>>> public_key = private_key.public_key() >>> public_key.verify(signature, data, ec.ECDSA(hashes.SHA256()))
As above, the
signature
is abytes
object whose contents are DER encoded as described in RFC 3279. It can be created from a raw(r,s)
pair by usingencode_dss_signature()
.If the signature is not valid, an
InvalidSignature
exception will be raised.If your data is too large to be passed in a single call, you can hash it separately and pass that value using
Prehashed
.>>> chosen_hash = hashes.SHA256() >>> hasher = hashes.Hash(chosen_hash) >>> hasher.update(b"data & ") >>> hasher.update(b"more data") >>> digest = hasher.finalize() >>> public_key.verify( ... sig, ... digest, ... ec.ECDSA(utils.Prehashed(chosen_hash)) ... )
Note
Although in this case the public key was derived from the private one, in a typical setting you will not possess the private key. The Key loading section explains how to load the public key from other sources.
- class cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateNumbers(private_value, public_numbers)[source]
New in version 0.5.
The collection of integers that make up an EC private key.
- public_numbers
-
The
EllipticCurvePublicNumbers
which makes up the EC public key associated with this EC private key.
- private_key()
Convert a collection of numbers into a private key suitable for doing actual cryptographic operations.
- Returns:
A new instance of
EllipticCurvePrivateKey
.
- class cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicNumbers(x, y, curve)[source]
Warning
The point represented by this object is not validated in any way until
EllipticCurvePublicNumbers.public_key()
is called and may not represent a valid point on the curve. You should not attempt to perform any computations using the values from this class until you have either validated it yourself or calledpublic_key()
successfully.New in version 0.5.
The collection of integers that make up an EC public key.
- curve
- Type:
The elliptic curve for this key.
- public_key()
Convert a collection of numbers into a public key suitable for doing actual cryptographic operations.
- Raises:
ValueError – Raised if the point is invalid for the curve.
- Returns:
A new instance of
EllipticCurvePublicKey
.
Elliptic Curve Key Exchange algorithm
- class cryptography.hazmat.primitives.asymmetric.ec.ECDH[source]
New in version 1.1.
The Elliptic Curve Diffie-Hellman Key Exchange algorithm standardized in NIST publication 800-56A.
For most applications the
shared_key
should be passed to a key derivation function. This allows mixing of additional information into the key, derivation of multiple keys, and destroys any structure that may be present.Note that while elliptic curve keys can be used for both signing and key exchange, this is bad cryptographic practice. Instead, users should generate separate signing and ECDH keys.
Warning
This example does not give forward secrecy and is only provided as a demonstration of the basic Diffie-Hellman construction. For real world applications always use the ephemeral form described after this example.
>>> from cryptography.hazmat.primitives import hashes >>> from cryptography.hazmat.primitives.asymmetric import ec >>> from cryptography.hazmat.primitives.kdf.hkdf import HKDF >>> # Generate a private key for use in the exchange. >>> server_private_key = ec.generate_private_key( ... ec.SECP384R1() ... ) >>> # In a real handshake the peer is a remote client. For this >>> # example we'll generate another local private key though. >>> peer_private_key = ec.generate_private_key( ... ec.SECP384R1() ... ) >>> shared_key = server_private_key.exchange( ... ec.ECDH(), peer_private_key.public_key()) >>> # Perform key derivation. >>> derived_key = HKDF( ... algorithm=hashes.SHA256(), ... length=32, ... salt=None, ... info=b'handshake data', ... ).derive(shared_key) >>> # And now we can demonstrate that the handshake performed in the >>> # opposite direction gives the same final value >>> same_shared_key = peer_private_key.exchange( ... ec.ECDH(), server_private_key.public_key()) >>> # Perform key derivation. >>> same_derived_key = HKDF( ... algorithm=hashes.SHA256(), ... length=32, ... salt=None, ... info=b'handshake data', ... ).derive(same_shared_key) >>> derived_key == same_derived_key True
ECDHE (or EECDH), the ephemeral form of this exchange, is strongly preferred over simple ECDH and provides forward secrecy when used. You must generate a new private key using
generate_private_key()
for eachexchange()
when performing an ECDHE key exchange. An example of the ephemeral form:>>> from cryptography.hazmat.primitives import hashes >>> from cryptography.hazmat.primitives.asymmetric import ec >>> from cryptography.hazmat.primitives.kdf.hkdf import HKDF >>> # Generate a private key for use in the exchange. >>> private_key = ec.generate_private_key( ... ec.SECP384R1() ... ) >>> # In a real handshake the peer_public_key will be received from the >>> # other party. For this example we'll generate another private key >>> # and get a public key from that. >>> peer_public_key = ec.generate_private_key( ... ec.SECP384R1() ... ).public_key() >>> shared_key = private_key.exchange(ec.ECDH(), peer_public_key) >>> # Perform key derivation. >>> derived_key = HKDF( ... algorithm=hashes.SHA256(), ... length=32, ... salt=None, ... info=b'handshake data', ... ).derive(shared_key) >>> # For the next handshake we MUST generate another private key. >>> private_key_2 = ec.generate_private_key( ... ec.SECP384R1() ... ) >>> peer_public_key_2 = ec.generate_private_key( ... ec.SECP384R1() ... ).public_key() >>> shared_key_2 = private_key_2.exchange(ec.ECDH(), peer_public_key_2) >>> derived_key_2 = HKDF( ... algorithm=hashes.SHA256(), ... length=32, ... salt=None, ... info=b'handshake data', ... ).derive(shared_key_2)
Elliptic Curves
Elliptic curves provide equivalent security at much smaller key sizes than other asymmetric cryptography systems such as RSA or DSA. For many operations elliptic curves are also significantly faster; elliptic curve diffie-hellman is faster than diffie-hellman.
Note
Curves with a size of less than 224 bits should not be used. You should strongly consider using curves of at least 224 bits.
Generally the NIST prime field (“P”) curves are significantly faster than the other types suggested by NIST at both signing and verifying with ECDSA.
Prime fields also minimize the number of security concerns for elliptic-curve cryptography. However, there is some concern that both the prime field and binary field (“B”) NIST curves may have been weakened during their generation.
Currently cryptography only supports NIST curves, none of which are considered “safe” by the SafeCurves project run by Daniel J. Bernstein and Tanja Lange.
All named curves are instances of EllipticCurve
.
- class cryptography.hazmat.primitives.asymmetric.ec.SECP256R1[source]
New in version 0.5.
SECG curve
secp256r1
. Also called NIST P-256.
- class cryptography.hazmat.primitives.asymmetric.ec.SECP384R1[source]
New in version 0.5.
SECG curve
secp384r1
. Also called NIST P-384.
- class cryptography.hazmat.primitives.asymmetric.ec.SECP521R1[source]
New in version 0.5.
SECG curve
secp521r1
. Also called NIST P-521.
- class cryptography.hazmat.primitives.asymmetric.ec.SECP224R1[source]
New in version 0.5.
SECG curve
secp224r1
. Also called NIST P-224.
- class cryptography.hazmat.primitives.asymmetric.ec.SECP192R1[source]
New in version 0.5.
SECG curve
secp192r1
. Also called NIST P-192.
- class cryptography.hazmat.primitives.asymmetric.ec.SECP256K1[source]
New in version 0.9.
SECG curve
secp256k1
.
- class cryptography.hazmat.primitives.asymmetric.ec.BrainpoolP256R1[source]
New in version 2.2.
Brainpool curve specified in RFC 5639. These curves are discouraged for new systems.
- class cryptography.hazmat.primitives.asymmetric.ec.BrainpoolP384R1[source]
New in version 2.2.
Brainpool curve specified in RFC 5639. These curves are discouraged for new systems.
- class cryptography.hazmat.primitives.asymmetric.ec.BrainpoolP512R1[source]
New in version 2.2.
Brainpool curve specified in RFC 5639. These curves are discouraged for new systems.
- class cryptography.hazmat.primitives.asymmetric.ec.SECT571K1[source]
New in version 0.5.
SECG curve
sect571k1
. Also called NIST K-571. These binary curves are discouraged for new systems.
- class cryptography.hazmat.primitives.asymmetric.ec.SECT409K1[source]
New in version 0.5.
SECG curve
sect409k1
. Also called NIST K-409. These binary curves are discouraged for new systems.
- class cryptography.hazmat.primitives.asymmetric.ec.SECT283K1[source]
New in version 0.5.
SECG curve
sect283k1
. Also called NIST K-283. These binary curves are discouraged for new systems.
- class cryptography.hazmat.primitives.asymmetric.ec.SECT233K1[source]
New in version 0.5.
SECG curve
sect233k1
. Also called NIST K-233. These binary curves are discouraged for new systems.
- class cryptography.hazmat.primitives.asymmetric.ec.SECT163K1[source]
New in version 0.5.
SECG curve
sect163k1
. Also called NIST K-163. These binary curves are discouraged for new systems.
- class cryptography.hazmat.primitives.asymmetric.ec.SECT571R1[source]
New in version 0.5.
SECG curve
sect571r1
. Also called NIST B-571. These binary curves are discouraged for new systems.
- class cryptography.hazmat.primitives.asymmetric.ec.SECT409R1[source]
New in version 0.5.
SECG curve
sect409r1
. Also called NIST B-409. These binary curves are discouraged for new systems.
- class cryptography.hazmat.primitives.asymmetric.ec.SECT283R1[source]
New in version 0.5.
SECG curve
sect283r1
. Also called NIST B-283. These binary curves are discouraged for new systems.
- class cryptography.hazmat.primitives.asymmetric.ec.SECT233R1[source]
New in version 0.5.
SECG curve
sect233r1
. Also called NIST B-233. These binary curves are discouraged for new systems.
- class cryptography.hazmat.primitives.asymmetric.ec.SECT163R2[source]
New in version 0.5.
SECG curve
sect163r2
. Also called NIST B-163. These binary curves are discouraged for new systems.
Key Interfaces
- class cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve[source]
New in version 0.5.
A named elliptic curve.
- key_size
- Type:
Size (in bits) of a secret scalar for the curve (as generated by
generate_private_key()
).
- class cryptography.hazmat.primitives.asymmetric.ec.EllipticCurveSignatureAlgorithm[source]
New in version 0.5.
Changed in version 1.6:
Prehashed
can now be used as analgorithm
.A signature algorithm for use with elliptic curve keys.
- algorithm
- Type:
The digest algorithm to be used with the signature scheme.
- class cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey[source]
New in version 0.5.
An elliptic curve private key for use with an algorithm such as ECDSA.
- exchange(algorithm, peer_public_key)[source]
New in version 1.1.
Performs a key exchange operation using the provided algorithm with the peer’s public key.
For most applications the
shared_key
should be passed to a key derivation function. This allows mixing of additional information into the key, derivation of multiple keys, and destroys any structure that may be present.- Parameters:
algorithm – The key exchange algorithm, currently only
ECDH
is supported.peer_public_key (EllipticCurvePublicKey) – The public key for the peer.
- Returns bytes:
A shared key.
- sign(data, signature_algorithm)[source]
New in version 1.5.
Sign one block of data which can be verified later by others using the public key.
- Parameters:
data (bytes-like) – The message string to sign.
signature_algorithm – An instance of
EllipticCurveSignatureAlgorithm
, such asECDSA
.
- Return bytes:
The signature as a
bytes
object, whose contents are DER encoded as described in RFC 3279. This can be decoded usingdecode_dss_signature()
, which returns the decoded tuple(r, s)
.
- curve
- Type:
The EllipticCurve that this key is on.
- key_size
New in version 1.9.
- Type:
Size (in bits) of a secret scalar for the curve (as generated by
generate_private_key()
).
- private_numbers()[source]
Create a
EllipticCurvePrivateNumbers
object.- Returns:
An
EllipticCurvePrivateNumbers
instance.
- private_bytes(encoding, format, encryption_algorithm)[source]
Allows serialization of the key to bytes. Encoding (
PEM
orDER
), format (TraditionalOpenSSL
,OpenSSH
orPKCS8
) and encryption algorithm (such asBestAvailableEncryption
orNoEncryption
) are chosen to define the exact serialization.- Parameters:
encoding – A value from the
Encoding
enum.format – A value from the
PrivateFormat
enum.encryption_algorithm – An instance of an object conforming to the
KeySerializationEncryption
interface.
- Return bytes:
Serialized key.
- class cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey[source]
New in version 0.5.
An elliptic curve public key.
- curve
- Type:
The elliptic curve for this key.
- public_numbers()[source]
Create a
EllipticCurvePublicNumbers
object.- Returns:
An
EllipticCurvePublicNumbers
instance.
- public_bytes(encoding, format)[source]
Allows serialization of the key data to bytes. When encoding the public key the encodings (
PEM
,DER
) and format (SubjectPublicKeyInfo
) are chosen to define the exact serialization. When encoding the point the encodingX962
should be used with the formats (UncompressedPoint
orCompressedPoint
).- Parameters:
encoding – A value from the
Encoding
enum.format – A value from the
PublicFormat
enum.
- Return bytes:
Serialized data.
- verify(signature, data, signature_algorithm)[source]
New in version 1.5.
Verify one block of data was signed by the private key associated with this public key.
- Parameters:
signature (bytes-like) – The DER-encoded signature to verify. A raw signature may be DER-encoded by splitting it into the
r
ands
components and passing them intoencode_dss_signature()
.data (bytes-like) – The message string that was signed.
signature_algorithm – An instance of
EllipticCurveSignatureAlgorithm
.
- Returns:
None
- Raises:
cryptography.exceptions.InvalidSignature – If the signature does not validate.
- key_size
New in version 1.9.
- Type:
Size (in bits) of a secret scalar for the curve (as generated by
generate_private_key()
).
- classmethod from_encoded_point(curve, data)[source]
New in version 2.5.
Decodes a byte string as described in SEC 1 v2.0 section 2.3.3 and returns an
EllipticCurvePublicKey
. This class method supports compressed points.- Parameters:
curve – An
EllipticCurve
instance.data (bytes) – The serialized point byte string.
- Returns:
An
EllipticCurvePublicKey
instance.- Raises:
ValueError – Raised when an invalid point is supplied.
TypeError – Raised when curve is not an
EllipticCurve
.
Serialization
This sample demonstrates how to generate a private key and serialize it.
>>> from cryptography.hazmat.primitives import serialization
>>> from cryptography.hazmat.primitives.asymmetric import ec
>>> private_key = ec.generate_private_key(ec.SECP384R1())
>>> serialized_private = private_key.private_bytes(
... encoding=serialization.Encoding.PEM,
... format=serialization.PrivateFormat.PKCS8,
... encryption_algorithm=serialization.BestAvailableEncryption(b'testpassword')
... )
>>> serialized_private.splitlines()[0]
b'-----BEGIN ENCRYPTED PRIVATE KEY-----'
You can also serialize the key without a password, by relying on
NoEncryption
.
The public key is serialized as follows:
>>> public_key = private_key.public_key()
>>> serialized_public = public_key.public_bytes(
... encoding=serialization.Encoding.PEM,
... format=serialization.PublicFormat.SubjectPublicKeyInfo
... )
>>> serialized_public.splitlines()[0]
b'-----BEGIN PUBLIC KEY-----'
This is the part that you would normally share with the rest of the world.
Key loading
This extends the sample in the previous section, assuming that the variables
serialized_private
and serialized_public
contain the respective keys
in PEM format.
>>> loaded_public_key = serialization.load_pem_public_key(
... serialized_public,
... )
>>> loaded_private_key = serialization.load_pem_private_key(
... serialized_private,
... # or password=None, if in plain text
... password=b'testpassword',
... )
Elliptic Curve Object Identifiers
- class cryptography.hazmat.primitives.asymmetric.ec.EllipticCurveOID[source]
New in version 2.4.
- SECP192R1
Corresponds to the dotted string
"1.2.840.10045.3.1.1"
.
- SECP224R1
Corresponds to the dotted string
"1.3.132.0.33"
.
- SECP256K1
Corresponds to the dotted string
"1.3.132.0.10"
.
- SECP256R1
Corresponds to the dotted string
"1.2.840.10045.3.1.7"
.
- SECP384R1
Corresponds to the dotted string
"1.3.132.0.34"
.
- SECP521R1
Corresponds to the dotted string
"1.3.132.0.35"
.
- BRAINPOOLP256R1
New in version 2.5.
Corresponds to the dotted string
"1.3.36.3.3.2.8.1.1.7"
.
- BRAINPOOLP384R1
New in version 2.5.
Corresponds to the dotted string
"1.3.36.3.3.2.8.1.1.11"
.
- BRAINPOOLP512R1
New in version 2.5.
Corresponds to the dotted string
"1.3.36.3.3.2.8.1.1.13"
.
- SECT163K1
New in version 2.5.
Corresponds to the dotted string
"1.3.132.0.1"
.
- SECT163R2
New in version 2.5.
Corresponds to the dotted string
"1.3.132.0.15"
.
- SECT233K1
New in version 2.5.
Corresponds to the dotted string
"1.3.132.0.26"
.
- SECT233R1
New in version 2.5.
Corresponds to the dotted string
"1.3.132.0.27"
.
- SECT283K1
New in version 2.5.
Corresponds to the dotted string
"1.3.132.0.16"
.
- SECT283R1
New in version 2.5.
Corresponds to the dotted string
"1.3.132.0.17"
.
- SECT409K1
New in version 2.5.
Corresponds to the dotted string
"1.3.132.0.36"
.
- SECT409R1
New in version 2.5.
Corresponds to the dotted string
"1.3.132.0.37"
.
- SECT571K1
New in version 2.5.
Corresponds to the dotted string
"1.3.132.0.38"
.
- SECT571R1
New in version 2.5.
Corresponds to the dotted string
"1.3.132.0.39"
.
- cryptography.hazmat.primitives.asymmetric.ec.get_curve_for_oid(oid)[source]
New in version 2.6.
A function that takes an
ObjectIdentifier
and returns the associated elliptic curve class.- Parameters:
oid – An instance of
ObjectIdentifier
.- Returns:
The matching elliptic curve class. The returned class conforms to the
EllipticCurve
interface.- Raises:
LookupError – Raised if no elliptic curve is found that matches the provided object identifier.