cryptography.hazmat.primitives.asymmetric.ec
generate_private_key(curve, backend)
0.5
Generate a new private key on curve
for use with backend
.
- param curve
An instance of
EllipticCurve
.- param backend
An instance of
~cryptography.hazmat.backends.interfaces.EllipticCurveBackend
.- returns
A new instance of
EllipticCurvePrivateKey
.
derive_private_key(private_value, curve, backend)
1.6
Derive a private key from private_value
on curve
for use with backend
.
- param int private_value
The secret scalar value.
- param curve
An instance of
EllipticCurve
.- param backend
An instance of
~cryptography.hazmat.backends.interfaces.EllipticCurveBackend
.- returns
A new instance of
EllipticCurvePrivateKey
.
0.5
The ECDSA signature algorithm first standardized in NIST publication FIPS 186-3, and later in FIPS 186-4.
- param algorithm
An instance of
~cryptography.hazmat.primitives.hashes.HashAlgorithm
.
>>> from cryptography.hazmat.backends import default_backend >>> from cryptography.hazmat.primitives import hashes >>> from cryptography.hazmat.primitives.asymmetric import ec >>> private_key = ec.generate_private_key( ... ec.SECP384R1(), default_backend() ... ) >>> 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 is DER encoded as described in 3279
. This can be decoded using ~cryptography.hazmat.primitives.asymmetric.utils.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 ~cryptography.hazmat.primitives.asymmetric.utils.Prehashed
.
>>> from cryptography.hazmat.primitives.asymmetric import utils >>> chosen_hash = hashes.SHA256() >>> hasher = hashes.Hash(chosen_hash, default_backend()) >>> 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 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()))
If the signature is not valid, an ~cryptography.exceptions.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 ~cryptography.hazmat.primitives.asymmetric.utils.Prehashed
.
>>> chosen_hash = hashes.SHA256() >>> hasher = hashes.Hash(chosen_hash, default_backend()) >>> 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.
0.5
The collection of integers that make up an EC private key.
public_numbers
- type
~cryptography.hazmat.primitives.asymmetric.ec.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(backend)
Convert a collection of numbers into a private key suitable for doing actual cryptographic operations.
- param backend
An instance of
~cryptography.hazmat.backends.interfaces.EllipticCurveBackend
.- returns
A new instance of
EllipticCurvePrivateKey
.
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.
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(backend)
Convert a collection of numbers into a public key suitable for doing actual cryptographic operations.
- param backend
An instance of
~cryptography.hazmat.backends.interfaces.EllipticCurveBackend
.- raises ValueError
Raised if the point is invalid for the curve.
- returns
A new instance of
EllipticCurvePublicKey
.
encode_point()
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.
from_encoded_point(curve, data)
1.1
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.
- param curve
An
~cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve
instance.- param bytes data
The serialized point byte string.
- returns
An
EllipticCurvePublicNumbers
instance.- raises ValueError
Raised on invalid point type or data length.
- raises TypeError
Raised when curve is not an
~cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve
.
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.
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.backends import default_backend >>> 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(), default_backend() ... ) >>> # 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(), default_backend() ... ) >>> 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', ... backend=default_backend() ... ).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', ... backend=default_backend() ... ).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 ~EllipticCurvePrivateKey.exchange
when performing an ECDHE key exchange. An example of the ephemeral form:
>>> from cryptography.hazmat.backends import default_backend >>> 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(), default_backend() ... ) >>> # 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(), default_backend() ... ).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', ... backend=default_backend() ... ).derive(shared_key) >>> # For the next handshake we MUST generate another private key. >>> private_key_2 = ec.generate_private_key( ... ec.SECP384R1(), default_backend() ... ) >>> peer_public_key_2 = ec.generate_private_key( ... ec.SECP384R1(), default_backend() ... ).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', ... backend=default_backend() ... ).derive(shared_key_2)
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
.
0.5
SECG curve secp256r1
. Also called NIST P-256.
0.5
SECG curve secp384r1
. Also called NIST P-384.
0.5
SECG curve secp521r1
. Also called NIST P-521.
0.5
SECG curve secp224r1
. Also called NIST P-224.
0.5
SECG curve secp192r1
. Also called NIST P-192.
0.9
SECG curve secp256k1
.
2.2
Brainpool curve specified in 5639
. These curves are discouraged for new systems.
2.2
Brainpool curve specified in 5639
. These curves are discouraged for new systems.
2.2
Brainpool curve specified in 5639
. These curves are discouraged for new systems.
0.5
SECG curve sect571k1
. Also called NIST K-571. These binary curves are discouraged for new systems.
0.5
SECG curve sect409k1
. Also called NIST K-409. These binary curves are discouraged for new systems.
0.5
SECG curve sect283k1
. Also called NIST K-283. These binary curves are discouraged for new systems.
0.5
SECG curve sect233k1
. Also called NIST K-233. These binary curves are discouraged for new systems.
0.5
SECG curve sect163k1
. Also called NIST K-163. These binary curves are discouraged for new systems.
0.5
SECG curve sect571r1
. Also called NIST B-571. These binary curves are discouraged for new systems.
0.5
SECG curve sect409r1
. Also called NIST B-409. These binary curves are discouraged for new systems.
0.5
SECG curve sect283r1
. Also called NIST B-283. These binary curves are discouraged for new systems.
0.5
SECG curve sect233r1
. Also called NIST B-233. These binary curves are discouraged for new systems.
0.5
SECG curve sect163r2
. Also called NIST B-163. These binary curves are discouraged for new systems.
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
).
0.5
1.6 ~cryptography.hazmat.primitives.asymmetric.utils.Prehashed
can now be used as an algorithm
.
A signature algorithm for use with elliptic curve keys.
algorithm
- type
~cryptography.hazmat.primitives.hashes.HashAlgorithm
or~cryptography.hazmat.primitives.asymmetric.utils.Prehashed
The digest algorithm to be used with the signature scheme.
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)
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.
- param algorithm
The key exchange algorithm, currently only
~cryptography.hazmat.primitives.asymmetric.ec.ECDH
is supported.- param EllipticCurvePublicKey peer_public_key
The public key for the peer.
- returns bytes
A shared key.
public_key()
- return
EllipticCurvePublicKey
The EllipticCurvePublicKey object for this private key.
sign(data, signature_algorithm)
1.5
Sign one block of data which can be verified later by others using the public key.
- param bytes data
The message string to sign.
- param signature_algorithm
An instance of
EllipticCurveSignatureAlgorithm
, such asECDSA
.- return bytes
Signature.
key_size
1.9
- type
int
Size (in bits
) of a secret scalar for the curve (as generated by generate_private_key
).
0.8
This interface contains additional methods relating to serialization. Any object with this interface also has all the methods from EllipticCurvePrivateKey
.
private_numbers()
Create a EllipticCurvePrivateNumbers
object.
- returns
An
EllipticCurvePrivateNumbers
instance.
private_bytes(encoding, format, encryption_algorithm)
Allows serialization of the key to bytes. Encoding ( ~cryptography.hazmat.primitives.serialization.Encoding.PEM
or ~cryptography.hazmat.primitives.serialization.Encoding.DER
), format ( ~cryptography.hazmat.primitives.serialization.PrivateFormat.TraditionalOpenSSL
or ~cryptography.hazmat.primitives.serialization.PrivateFormat.PKCS8
) and encryption algorithm (such as ~cryptography.hazmat.primitives.serialization.BestAvailableEncryption
or ~cryptography.hazmat.primitives.serialization.NoEncryption
) are chosen to define the exact serialization.
- param encoding
A value from the
~cryptography.hazmat.primitives.serialization.Encoding
enum.- param format
A value from the
~cryptography.hazmat.primitives.serialization.PrivateFormat
enum.- param encryption_algorithm
An instance of an object conforming to the
~cryptography.hazmat.primitives.serialization.KeySerializationEncryption
interface.- return bytes
Serialized key.
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 to bytes. Encoding ( ~cryptography.hazmat.primitives.serialization.Encoding.PEM
or ~cryptography.hazmat.primitives.serialization.Encoding.DER
) and format ( ~cryptography.hazmat.primitives.serialization.PublicFormat.SubjectPublicKeyInfo
) are chosen to define the exact serialization.
- param encoding
A value from the
~cryptography.hazmat.primitives.serialization.Encoding
enum.- param format
A value from the
~cryptography.hazmat.primitives.serialization.PublicFormat
enum.- return bytes
Serialized key.
verify(signature, data, signature_algorithm)
1.5
Verify one block of data was signed by the private key associated with this public key.
- param bytes signature
The signature to verify.
- param bytes data
The message string that was signed.
- param signature_algorithm
An instance of
EllipticCurveSignatureAlgorithm
.- raises cryptography.exceptions.InvalidSignature
If the signature does not validate.
key_size
1.9
- type
int
Size (in bits
) of a secret scalar for the curve (as generated by generate_private_key
).
0.6
Alias for EllipticCurvePublicKey
.
This sample demonstrates how to generate a private key and serialize it.
>>> from cryptography.hazmat.backends import default_backend >>> from cryptography.hazmat.primitives import hashes >>> from cryptography.hazmat.primitives.asymmetric import ec >>> from cryptography.hazmat.primitives import serialization
>>> private_key = ec.generate_private_key(ec.SECP384R1(), default_backend())
>>> 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 ~cryptography.hazmat.primitives.serialization.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.
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, ... backend=default_backend() ... )
>>> loaded_private_key = serialization.load_pem_private_key( ... serialized_private, ... # or password=None, if in plain text ... password=b'testpassword', ... backend=default_backend() ... )
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"
.