crypto — Generic cryptographic module

Danger

This module is pending deprecation, use pyca/cryptography instead.

pyca/cryptography is likely a better choice than using this module. It contains a complete set of cryptographic primitives as well as a significantly better and more powerful X509 API. If necessary you can convert to and from cryptography objects using the to_cryptography and from_cryptography methods on X509, X509Req, CRL, and PKey.

Elliptic curves

OpenSSL.crypto.get_elliptic_curves() set[_EllipticCurve]

Return a set of objects representing the elliptic curves supported in the OpenSSL build in use.

The curve objects have a unicode name attribute by which they identify themselves.

The curve objects are useful as values for the argument accepted by Context.set_tmp_ecdh() to specify which elliptical curve should be used for ECDHE key exchange.

OpenSSL.crypto.get_elliptic_curve(name: str) _EllipticCurve

Return a single curve object selected by name.

See get_elliptic_curves() for information about curve objects.

Parameters:

name (unicode) – The OpenSSL short name identifying the curve object to retrieve.

If the named curve is not supported then ValueError is raised.

Serialization and deserialization

The following serialization functions take one of these constants to determine the format.

OpenSSL.crypto.FILETYPE_PEM

FILETYPE_PEM serializes data to a Base64-encoded encoded representation of the underlying ASN.1 data structure. This representation includes delimiters that define what data structure is contained within the Base64-encoded block: for example, for a certificate, the delimiters are -----BEGIN CERTIFICATE----- and -----END CERTIFICATE-----.

OpenSSL.crypto.FILETYPE_ASN1

FILETYPE_ASN1 serializes data to the underlying ASN.1 data structure. The format used by FILETYPE_ASN1 is also sometimes referred to as DER.

Certificates

OpenSSL.crypto.dump_certificate(type: int, cert: X509) bytes

Dump the certificate cert into a buffer string encoded with the type type.

Parameters:
  • type – The file type (one of FILETYPE_PEM, FILETYPE_ASN1, or FILETYPE_TEXT)

  • cert – The certificate to dump

Returns:

The buffer with the dumped certificate in

OpenSSL.crypto.load_certificate(type: int, buffer: bytes) X509

Load a certificate (X509) from the string buffer encoded with the type type.

Parameters:
  • type – The file type (one of FILETYPE_PEM, FILETYPE_ASN1)

  • buffer (bytes) – The buffer the certificate is stored in

Returns:

The X509 object

Certificate signing requests

OpenSSL.crypto.dump_certificate_request(type: int, req: <cryptography.utils._DeprecatedValue object at 0x7f865f4d5f30>) bytes

Dump the certificate request req into a buffer string encoded with the type type.

Parameters:
  • type – The file type (one of FILETYPE_PEM, FILETYPE_ASN1)

  • req – The certificate request to dump

Returns:

The buffer with the dumped certificate request in

Deprecated since version 24.2.0: Use cryptography.x509.CertificateSigningRequest instead.

OpenSSL.crypto.load_certificate_request(type: int, buffer: bytes) <cryptography.utils._DeprecatedValue object at 0x7f865f4d5f30>

Load a certificate request (X509Req) from the string buffer encoded with the type type.

Parameters:
  • type – The file type (one of FILETYPE_PEM, FILETYPE_ASN1)

  • buffer – The buffer the certificate request is stored in

Returns:

The X509Req object

Deprecated since version 24.2.0: Use cryptography.x509.load_der_x509_csr or cryptography.x509.load_pem_x509_csr instead.

Private keys

OpenSSL.crypto.dump_privatekey(type: int, pkey: PKey, cipher: str | None = None, passphrase: bytes | Callable[[...], bytes] | None = None) bytes

Dump the private key pkey into a buffer string encoded with the type type. Optionally (if type is FILETYPE_PEM) encrypting it using cipher and passphrase.

Parameters:
  • type – The file type (one of FILETYPE_PEM, FILETYPE_ASN1, or FILETYPE_TEXT)

  • pkey (PKey) – The PKey to dump

  • cipher – (optional) if encrypted PEM format, the cipher to use

  • passphrase – (optional) if encrypted PEM format, this can be either the passphrase to use, or a callback for providing the passphrase.

Returns:

The buffer with the dumped key in

Return type:

bytes

OpenSSL.crypto.load_privatekey(type: int, buffer: str | bytes, passphrase: bytes | Callable[[...], bytes] | None = None) PKey

Load a private key (PKey) from the string buffer encoded with the type type.

Parameters:
  • type – The file type (one of FILETYPE_PEM, FILETYPE_ASN1)

  • buffer – The buffer the key is stored in

  • passphrase – (optional) if encrypted PEM format, this can be either the passphrase to use, or a callback for providing the passphrase.

Returns:

The PKey object

Public keys

OpenSSL.crypto.dump_publickey(type: int, pkey: PKey) bytes

Dump a public key to a buffer.

Parameters:
Returns:

The buffer with the dumped key in it.

Return type:

bytes

OpenSSL.crypto.load_publickey(type: int, buffer: str | bytes) PKey

Load a public key from a buffer.

Parameters:
  • type – The file type (one of FILETYPE_PEM, FILETYPE_ASN1).

  • buffer (A Python string object, either unicode or bytestring.) – The buffer the key is stored in.

Returns:

The PKey object.

Return type:

PKey

X509 objects

class OpenSSL.crypto.X509

An X.509 certificate.

add_extensions(extensions: Iterable[X509Extension]) None

Add extensions to the certificate.

Parameters:

extensions (An iterable of X509Extension objects.) – The extensions to add.

Returns:

None

digest(digest_name: str) bytes

Return the digest of the X509 object.

Parameters:

digest_name (str) – The name of the digest algorithm to use.

Returns:

The digest of the object, formatted as b":"-delimited hex pairs.

Return type:

bytes

classmethod from_cryptography(crypto_cert: Certificate) X509

Construct based on a cryptography crypto_cert.

Parameters:

crypto_key (cryptography.x509.Certificate) – A cryptography X.509 certificate.

Return type:

X509

Added in version 17.1.0.

get_extension(index: int) X509Extension

Get a specific extension of the certificate by index.

Extensions on a certificate are kept in order. The index parameter selects which extension will be returned.

Parameters:

index (int) – The index of the extension to retrieve.

Returns:

The extension at the specified index.

Return type:

X509Extension

Raises:

IndexError – If the extension index was out of bounds.

Added in version 0.12.

get_extension_count() int

Get the number of extensions on this certificate.

Returns:

The number of extensions.

Return type:

int

Added in version 0.12.

get_issuer() X509Name

Return the issuer of this certificate.

This creates a new X509Name that wraps the underlying issuer name field on the certificate. Modifying it will modify the underlying certificate, and will have the effect of modifying any other X509Name that refers to this issuer.

Returns:

The issuer of this certificate.

Return type:

X509Name

get_notAfter() bytes | None

Get the timestamp at which the certificate stops being valid.

The timestamp is formatted as an ASN.1 TIME:

YYYYMMDDhhmmssZ
Returns:

A timestamp string, or None if there is none.

Return type:

bytes or NoneType

get_notBefore() bytes | None

Get the timestamp at which the certificate starts being valid.

The timestamp is formatted as an ASN.1 TIME:

YYYYMMDDhhmmssZ
Returns:

A timestamp string, or None if there is none.

Return type:

bytes or NoneType

get_pubkey() PKey

Get the public key of the certificate.

Returns:

The public key.

Return type:

PKey

get_serial_number() int

Return the serial number of this certificate.

Returns:

The serial number.

Return type:

int

get_signature_algorithm() bytes

Return the signature algorithm used in the certificate.

Returns:

The name of the algorithm.

Return type:

bytes

Raises:

ValueError – If the signature algorithm is undefined.

Added in version 0.13.

get_subject() X509Name

Return the subject of this certificate.

This creates a new X509Name that wraps the underlying subject name field on the certificate. Modifying it will modify the underlying certificate, and will have the effect of modifying any other X509Name that refers to this subject.

Returns:

The subject of this certificate.

Return type:

X509Name

get_version() int

Return the version number of the certificate.

Returns:

The version number of the certificate.

Return type:

int

gmtime_adj_notAfter(amount: int) None

Adjust the time stamp on which the certificate stops being valid.

Parameters:

amount (int) – The number of seconds by which to adjust the timestamp.

Returns:

None

gmtime_adj_notBefore(amount: int) None

Adjust the timestamp on which the certificate starts being valid.

Parameters:

amount – The number of seconds by which to adjust the timestamp.

Returns:

None

has_expired() bool

Check whether the certificate has expired.

Returns:

True if the certificate has expired, False otherwise.

Return type:

bool

set_issuer(issuer: X509Name) None

Set the issuer of this certificate.

Parameters:

issuer (X509Name) – The issuer.

Returns:

None

set_notAfter(when: bytes) None

Set the timestamp at which the certificate stops being valid.

The timestamp is formatted as an ASN.1 TIME:

YYYYMMDDhhmmssZ
Parameters:

when (bytes) – A timestamp string.

Returns:

None

set_notBefore(when: bytes) None

Set the timestamp at which the certificate starts being valid.

The timestamp is formatted as an ASN.1 TIME:

YYYYMMDDhhmmssZ
Parameters:

when (bytes) – A timestamp string.

Returns:

None

set_pubkey(pkey: PKey) None

Set the public key of the certificate.

Parameters:

pkey (PKey) – The public key.

Returns:

None

set_serial_number(serial: int) None

Set the serial number of the certificate.

Parameters:

serial (int) – The new serial number.

Returns:

:py:data`None`

set_subject(subject: X509Name) None

Set the subject of this certificate.

Parameters:

subject (X509Name) – The subject.

Returns:

None

set_version(version: int) None

Set the version number of the certificate. Note that the version value is zero-based, eg. a value of 0 is V1.

Parameters:

version (int) – The version number of the certificate.

Returns:

None

sign(pkey: PKey, digest: str) None

Sign the certificate with this key and digest type.

Parameters:
  • pkey (PKey) – The key to sign with.

  • digest (str) – The name of the message digest to use.

Returns:

None

subject_name_hash() bytes

Return the hash of the X509 subject.

Returns:

The hash of the subject.

Return type:

bytes

to_cryptography() Certificate

Export as a cryptography certificate.

Return type:

cryptography.x509.Certificate

Added in version 17.1.0.

X509Name objects

class OpenSSL.crypto.X509Name(name: X509Name)

An X.509 Distinguished Name.

Variables:
  • countryName – The country of the entity.

  • C – Alias for countryName.

  • stateOrProvinceName – The state or province of the entity.

  • ST – Alias for stateOrProvinceName.

  • localityName – The locality of the entity.

  • L – Alias for localityName.

  • organizationName – The organization name of the entity.

  • O – Alias for organizationName.

  • organizationalUnitName – The organizational unit of the entity.

  • OU – Alias for organizationalUnitName

  • commonName – The common name of the entity.

  • CN – Alias for commonName.

  • emailAddress – The e-mail address of the entity.

__eq__(other: Any) bool

Return self==value.

__ge__(other)

Return a >= b. Computed by @total_ordering from (not a < b).

__gt__(other)

Return a > b. Computed by @total_ordering from (not a < b) and (a != b).

__init__(name: X509Name) None

Create a new X509Name, copying the given X509Name instance.

Parameters:

name (X509Name) – The name to copy.

__le__(other)

Return a <= b. Computed by @total_ordering from (a < b) or (a == b).

__lt__(other: Any) bool

Return self<value.

__setattr__(name: str, value: Any) None

Implement setattr(self, name, value).

der() bytes

Return the DER encoding of this name.

Returns:

The DER encoded form of this name.

Return type:

bytes

get_components() list[tuple[bytes, bytes]]

Returns the components of this name, as a sequence of 2-tuples.

Returns:

The components of this name.

Return type:

list of name, value tuples.

hash() int

Return an integer representation of the first four bytes of the MD5 digest of the DER representation of the name.

This is the Python equivalent of OpenSSL’s X509_NAME_hash.

Returns:

The (integer) hash of this name.

Return type:

int

X509Req objects

class OpenSSL.crypto.X509Req

An X.509 certificate signing requests.

Deprecated since version 24.2.0: Use cryptography.x509.CertificateSigningRequest instead.

__init__() None
add_extensions(extensions: Iterable[X509Extension]) None

Add extensions to the certificate signing request.

Parameters:

extensions (iterable of X509Extension) – The X.509 extensions to add.

Returns:

None

classmethod from_cryptography(crypto_req: CertificateSigningRequest) <cryptography.utils._DeprecatedValue object at 0x7f865f4d5f30>

Construct based on a cryptography crypto_req.

Parameters:

crypto_req (cryptography.x509.CertificateSigningRequest) – A cryptography X.509 certificate signing request

Return type:

X509Req

Added in version 17.1.0.

get_extensions() list[X509Extension]

Get X.509 extensions in the certificate signing request.

Returns:

The X.509 extensions in this request.

Return type:

list of X509Extension objects.

Added in version 0.15.

get_pubkey() PKey

Get the public key of the certificate signing request.

Returns:

The public key.

Return type:

PKey

get_subject() X509Name

Return the subject of this certificate signing request.

This creates a new X509Name that wraps the underlying subject name field on the certificate signing request. Modifying it will modify the underlying signing request, and will have the effect of modifying any other X509Name that refers to this subject.

Returns:

The subject of this certificate signing request.

Return type:

X509Name

get_version() int

Get the version subfield (RFC 2459, section 4.1.2.1) of the certificate request.

Returns:

The value of the version subfield.

Return type:

int

set_pubkey(pkey: PKey) None

Set the public key of the certificate signing request.

Parameters:

pkey (PKey) – The public key to use.

Returns:

None

set_version(version: int) None

Set the version subfield (RFC 2986, section 4.1) of the certificate request.

Parameters:

version (int) – The version number.

Returns:

None

sign(pkey: PKey, digest: str) None

Sign the certificate signing request with this key and digest type.

Parameters:
  • pkey (PKey) – The key pair to sign with.

  • digest (str) – The name of the message digest to use for the signature, e.g. "sha256".

Returns:

None

to_cryptography() CertificateSigningRequest

Export as a cryptography certificate signing request.

Return type:

cryptography.x509.CertificateSigningRequest

Added in version 17.1.0.

verify(pkey: PKey) bool

Verifies the signature on this certificate signing request.

Parameters:

key (PKey) – A public key.

Returns:

True if the signature is correct.

Return type:

bool

Raises:

OpenSSL.crypto.Error – If the signature is invalid or there is a problem verifying the signature.

X509Store objects

class OpenSSL.crypto.X509Store

An X.509 store.

An X.509 store is used to describe a context in which to verify a certificate. A description of a context may include a set of certificates to trust, a set of certificate revocation lists, verification flags and more.

An X.509 store, being only a description, cannot be used by itself to verify a certificate. To carry out the actual verification process, see X509StoreContext.

add_cert(cert: X509) None

Adds a trusted certificate to this store.

Adding a certificate with this method adds this certificate as a trusted certificate.

Parameters:

cert (X509) – The certificate to add to this store.

Raises:
Returns:

None if the certificate was added successfully.

add_crl(crl: CertificateRevocationList) None

Add a certificate revocation list to this store.

The certificate revocation lists added to a store will only be used if the associated flags are configured to check certificate revocation lists.

Added in version 16.1.0.

Parameters:

crl (cryptography.x509.CertificateRevocationList) – The certificate revocation list to add to this store.

Returns:

None if the certificate revocation list was added successfully.

load_locations(cafile: str | bytes | PathLike, capath: str | bytes | PathLike | None = None) None

Let X509Store know where we can find trusted certificates for the certificate chain. Note that the certificates have to be in PEM format.

If capath is passed, it must be a directory prepared using the c_rehash tool included with OpenSSL. Either, but not both, of cafile or capath may be None.

Note

Both cafile and capath may be set simultaneously.

Call this method multiple times to add more than one location. For example, CA certificates, and certificate revocation list bundles may be passed in cafile in subsequent calls to this method.

Added in version 20.0.

Parameters:
  • cafile – In which file we can find the certificates (bytes or unicode).

  • capath – In which directory we can find the certificates (bytes or unicode).

Returns:

None if the locations were set successfully.

Raises:

OpenSSL.crypto.Error – If both cafile and capath is None or the locations could not be set for any reason.

set_flags(flags: int) None

Set verification flags to this store.

Verification flags can be combined by oring them together.

Note

Setting a verification flag sometimes requires clients to add additional information to the store, otherwise a suitable error will be raised.

For example, in setting flags to enable CRL checking a suitable CRL must be added to the store otherwise an error will be raised.

Added in version 16.1.0.

Parameters:

flags (int) – The verification flags to set on this store. See X509StoreFlags for available constants.

Returns:

None if the verification flags were successfully set.

set_time(vfy_time: datetime) None

Set the time against which the certificates are verified.

Normally the current time is used.

Note

For example, you can determine if a certificate was valid at a given time.

Added in version 17.0.0.

Parameters:

vfy_time (datetime) – The verification time to set on this store.

Returns:

None if the verification time was successfully set.

X509StoreContextError objects

class OpenSSL.crypto.X509StoreContextError(message: str, errors: list[Any], certificate: X509)

An exception raised when an error occurred while verifying a certificate using OpenSSL.X509StoreContext.verify_certificate.

Variables:

certificate – The certificate which caused verificate failure.

X509StoreContext objects

class OpenSSL.crypto.X509StoreContext(store: X509Store, certificate: X509, chain: Sequence[X509] | None = None)

An X.509 store context.

An X.509 store context is used to carry out the actual verification process of a certificate in a described context. For describing such a context, see X509Store.

Parameters:
  • store (X509Store) – The certificates which will be trusted for the purposes of any verifications.

  • certificate (X509) – The certificate to be verified.

  • chain (list of X509) – List of untrusted certificates that may be used for building the certificate chain. May be None.

get_verified_chain() list[X509]

Verify a certificate in a context and return the complete validated chain.

Raises:

X509StoreContextError – If an error occurred when validating a certificate in the context. Sets certificate attribute to indicate which certificate caused the error.

Added in version 20.0.

set_store(store: X509Store) None

Set the context’s X.509 store.

Added in version 0.15.

Parameters:

store (X509Store) – The store description which will be used for the purposes of any future verifications.

verify_certificate() None

Verify a certificate in a context.

Added in version 0.15.

Raises:

X509StoreContextError – If an error occurred when validating a certificate in the context. Sets certificate attribute to indicate which certificate caused the error.

X509StoreFlags constants

class OpenSSL.crypto.X509StoreFlags

Flags for X509 verification, used to change the behavior of X509Store.

See OpenSSL Verification Flags for details.

CRL_CHECK
CRL_CHECK_ALL
IGNORE_CRITICAL
X509_STRICT
ALLOW_PROXY_CERTS
POLICY_CHECK
EXPLICIT_POLICY
INHIBIT_MAP
NOTIFY_POLICY
CHECK_SS_SIGNATURE
PARTIAL_CHAIN

PKey objects

class OpenSSL.crypto.PKey

A class representing an DSA or RSA public key or key pair.

bits() int

Returns the number of bits of the key

Returns:

The number of bits of the key.

check() bool

Check the consistency of an RSA private key.

This is the Python equivalent of OpenSSL’s RSA_check_key.

Returns:

True if key is consistent.

Raises:
  • OpenSSL.crypto.Error – if the key is inconsistent.

  • TypeError – if the key is of a type which cannot be checked. Only RSA keys can currently be checked.

classmethod from_cryptography_key(crypto_key: DSAPrivateKey | EllipticCurvePrivateKey | Ed25519PrivateKey | Ed448PrivateKey | RSAPrivateKey | DSAPublicKey | EllipticCurvePublicKey | Ed25519PublicKey | Ed448PublicKey | RSAPublicKey) PKey

Construct based on a cryptography crypto_key.

Parameters:

crypto_key (One of cryptography’s key interfaces.) – A cryptography key.

Return type:

PKey

Added in version 16.1.0.

generate_key(type: int, bits: int) None

Generate a key pair of the given type, with the given number of bits.

This generates a key “into” the this object.

Parameters:
  • type (TYPE_RSA or TYPE_DSA) – The key type.

  • bits (int >= 0) – The number of bits.

Raises:
  • TypeError – If type or bits isn’t of the appropriate type.

  • ValueError – If the number of bits isn’t an integer of the appropriate size.

Returns:

None

to_cryptography_key() DSAPrivateKey | EllipticCurvePrivateKey | Ed25519PrivateKey | Ed448PrivateKey | RSAPrivateKey | DSAPublicKey | EllipticCurvePublicKey | Ed25519PublicKey | Ed448PublicKey | RSAPublicKey

Export as a cryptography key.

Return type:

One of cryptography’s key interfaces.

Added in version 16.1.0.

type() int

Returns the type of the key

Returns:

The type of the key.

OpenSSL.crypto.TYPE_RSA
OpenSSL.crypto.TYPE_DSA

Key type constants.

X509Extension objects

class OpenSSL.crypto.X509Extension(type_name: bytes, critical: bool, value: bytes, subject: X509 | None = None, issuer: X509 | None = None)

An X.509 v3 certificate extension.

Deprecated since version 23.3.0: Use cryptography’s X509 APIs instead.

__init__(type_name: bytes, critical: bool, value: bytes, subject: X509 | None = None, issuer: X509 | None = None) None

Initializes an X509 extension.

Parameters:
  • type_name (bytes) – The name of the type of extension to create.

  • critical (bool) – A flag indicating whether this is a critical extension.

  • value (bytes) – The OpenSSL textual representation of the extension’s value.

  • subject (X509) – Optional X509 certificate to use as subject.

  • issuer (X509) – Optional X509 certificate to use as issuer.

__str__() str
Returns:

a nice text representation of the extension

get_critical() bool

Returns the critical field of this X.509 extension.

Returns:

The critical field.

get_data() bytes

Returns the data of the X509 extension, encoded as ASN.1.

Returns:

The ASN.1 encoded data of this X509 extension.

Return type:

bytes

Added in version 0.12.

get_short_name() bytes

Returns the short type name of this X.509 extension.

The result is a byte string such as b"basicConstraints".

Returns:

The short type name.

Return type:

bytes

Added in version 0.12.

Exceptions

exception OpenSSL.crypto.Error

Generic exception used in the crypto module.

Digest names

Several of the functions and methods in this module take a digest name. These must be strings describing a digest algorithm supported by OpenSSL (by EVP_get_digestbyname, specifically). For example, b"sha256" or b"sha384".

More information and a list of these digest names can be found in the EVP_DigestInit(3) man page of your OpenSSL installation. This page can be found online for the latest version of OpenSSL: https://www.openssl.org/docs/manmaster/man3/EVP_DigestInit.html