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)

New in version 1.6.

Derive a private key from private_value on curve.

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)

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.

>>> 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 a bytes object, whose contents are DER encoded as described in RFC 3279. This can be decoded using decode_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 a bytes object whose contents are DER encoded as described in RFC 3279. It can be created from a raw (r,s) pair by using encode_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)

New in version 0.5.

The collection of integers that make up an EC private key.

public_numbers
Type:

EllipticCurvePublicNumbers

The EllipticCurvePublicNumbers which makes up the EC public key associated with this EC private key.

private_value
Type:

int

The private value.

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)

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 called public_key() successfully.

New in version 0.5.

The collection of integers that make up an EC public key.

curve
Type:

EllipticCurve

The elliptic curve for this key.

x
Type:

int

The affine x component of the public point used for verifying.

y
Type:

int

The affine y component of the public point used for verifying.

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.

encode_point()

Warning

This method is deprecated as of version 2.5. Callers should migrate to using public_bytes().

New in version 1.1.

Encodes an elliptic curve point to a byte string as described in SEC 1 v2.0 section 2.3.3. This method only supports uncompressed points.

Return bytes:

The encoded point.

classmethod from_encoded_point(curve, data)

New in version 1.1.

Note

This has been deprecated in favor of from_encoded_point()

Decodes a byte string as described in SEC 1 v2.0 section 2.3.3 and returns an EllipticCurvePublicNumbers. This method only supports uncompressed points.

Parameters:
Returns:

An EllipticCurvePublicNumbers instance.

Raises:

Elliptic Curve Key Exchange algorithm

class cryptography.hazmat.primitives.asymmetric.ec.ECDH

New in version 1.1.

The Elliptic Curve Diffie-Hellman Key Exchange algorithm first standardized in NIST publication 800-56A, and later in 800-56Ar2.

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 each exchange() 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

New in version 0.5.

SECG curve secp256r1. Also called NIST P-256.

class cryptography.hazmat.primitives.asymmetric.ec.SECP384R1

New in version 0.5.

SECG curve secp384r1. Also called NIST P-384.

class cryptography.hazmat.primitives.asymmetric.ec.SECP521R1

New in version 0.5.

SECG curve secp521r1. Also called NIST P-521.

class cryptography.hazmat.primitives.asymmetric.ec.SECP224R1

New in version 0.5.

SECG curve secp224r1. Also called NIST P-224.

class cryptography.hazmat.primitives.asymmetric.ec.SECP192R1

New in version 0.5.

SECG curve secp192r1. Also called NIST P-192.

class cryptography.hazmat.primitives.asymmetric.ec.SECP256K1

New in version 0.9.

SECG curve secp256k1.

class cryptography.hazmat.primitives.asymmetric.ec.BrainpoolP256R1

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

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

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

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

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

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

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

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

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

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

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

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

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

New in version 0.5.

A named elliptic curve.

name
Type:

str

The name of the curve. Usually the name used for the ASN.1 OID such as secp256k1.

key_size
Type:

int

Size (in bits) of a secret scalar for the curve (as generated by generate_private_key()).

class cryptography.hazmat.primitives.asymmetric.ec.EllipticCurveSignatureAlgorithm

New in version 0.5.

Changed in version 1.6: Prehashed can now be used as an algorithm.

A signature algorithm for use with elliptic curve keys.

algorithm
Type:

HashAlgorithm or Prehashed

The digest algorithm to be used with the signature scheme.

class cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey

New in version 0.5.

An elliptic curve private key for use with an algorithm such as ECDSA or EdDSA. An elliptic curve private key that is not an opaque key also implements EllipticCurvePrivateKeyWithSerialization to provide serialization methods.

exchange(algorithm, peer_public_key)

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.

public_key()
Returns:

EllipticCurvePublicKey

The EllipticCurvePublicKey object for this private key.

sign(data, signature_algorithm)

New in version 1.5.

Sign one block of data which can be verified later by others using the public key.

Parameters:
Return bytes:

The signature as a bytes object, whose contents are DER encoded as described in RFC 3279. This can be decoded using decode_dss_signature(), which returns the decoded tuple (r, s).

curve
Type:

EllipticCurve

The EllipticCurve that this key is on.

key_size

New in version 1.9.

Type:

int

Size (in bits) of a secret scalar for the curve (as generated by generate_private_key()).

private_numbers()

Create a EllipticCurvePrivateNumbers object.

Returns:

An EllipticCurvePrivateNumbers instance.

private_bytes(encoding, format, encryption_algorithm)

Allows serialization of the key to bytes. Encoding ( PEM or DER), format ( TraditionalOpenSSL, OpenSSH or PKCS8) and encryption algorithm (such as BestAvailableEncryption or NoEncryption) are chosen to define the exact serialization.

Parameters:
Return bytes:

Serialized key.

class cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKeyWithSerialization

New in version 0.8.

Alias for EllipticCurvePrivateKey.

class cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey

New in version 0.5.

An elliptic curve public key.

curve
Type:

EllipticCurve

The elliptic curve for this key.

public_numbers()

Create a EllipticCurvePublicNumbers object.

Returns:

An EllipticCurvePublicNumbers instance.

public_bytes(encoding, format)

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 encoding X962 should be used with the formats ( UncompressedPoint or CompressedPoint ).

Parameters:
Return bytes:

Serialized data.

verify(signature, data, signature_algorithm)

New in version 1.5.

Verify one block of data was signed by the private key associated with this public key.

Parameters:
Raises:

cryptography.exceptions.InvalidSignature – If the signature does not validate.

key_size

New in version 1.9.

Type:

int

Size (in bits) of a secret scalar for the curve (as generated by generate_private_key()).

classmethod from_encoded_point(curve, data)

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:
Returns:

An EllipticCurvePublicKey instance.

Raises:
class cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKeyWithSerialization

New in version 0.6.

Alias for EllipticCurvePublicKey.

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

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)

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.