crypto — Generic cryptographic module

Note

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

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)

Return a single curve object selected by name.

See get_elliptic_curves() for information about curve objects.

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, cert)

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

OpenSSL.crypto.load_certificate(type, buffer)

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

Certificate signing requests

OpenSSL.crypto.dump_certificate_request(type, req)

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

OpenSSL.crypto.load_certificate_request(type, buffer)

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

Private keys

OpenSSL.crypto.dump_privatekey(type, pkey, cipher=None, passphrase=None)

Dump a private key to a buffer

Parameters:
  • type – The file type (one of FILETYPE_PEM, FILETYPE_ASN1, or FILETYPE_TEXT)
  • 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:

str

OpenSSL.crypto.load_privatekey(type, buffer[, passphrase])

Load a private key (PKey) from the string buffer encoded with the type type (must be one of FILETYPE_PEM and FILETYPE_ASN1).

passphrase must be either a string or a callback for providing the pass phrase.

Public keys

Certificate revocation lists

OpenSSL.crypto.load_crl(type, buffer)

Load Certificate Revocation List (CRL) data from a string buffer. buffer encoded with the type type. The type type must either FILETYPE_PEM or FILETYPE_ASN1).

OpenSSL.crypto.load_pkcs7_data(type, buffer)

Load pkcs7 data from the string buffer encoded with the type type. The type type must either FILETYPE_PEM or FILETYPE_ASN1).

OpenSSL.crypto.load_pkcs12(buffer[, passphrase])

Load pkcs12 data from the string buffer. If the pkcs12 structure is encrypted, a passphrase must be included. The MAC is always checked and thus required.

See also the man page for the C function PKCS12_parse().

Signing and verifying signatures

OpenSSL.crypto.sign(key, data, digest)

Sign a data string using the given key and message digest.

key is a PKey instance. data is a str instance. digest is a str naming a supported message digest type, for example b"sha256".

New in version 0.11.

OpenSSL.crypto.verify(certificate, signature, data, digest)

Verify the signature for a data string.

certificate is a X509 instance corresponding to the private key which generated the signature. signature is a str instance giving the signature itself. data is a str instance giving the data to which the signature applies. digest is a str instance naming the message digest type of the signature, for example b"sha256".

New in version 0.11.

X509 objects

class OpenSSL.crypto.X509
add_extensions(extensions)

Add extensions to the certificate.

Parameters:extensions – a sequence of X509Extension objects
Returns:None
digest(digest_name)

Return the digest of the X509 object.

Parameters:digest_name (bytes) – The name of the digest algorithm to use.
Returns:The digest of the object
get_extension(index)

Get a specific extension of the certificate by index.

Parameters:index – The index of the extension to retrieve.
Returns:The X509Extension object at the specified index.
get_extension_count()

Get the number of extensions on the certificate.

Returns:The number of extensions as an integer.
get_issuer()

Create an X509Name object for the issuer of the certificate

Returns:An X509Name object
get_notAfter()

Retrieve the time stamp for when the certificate stops being valid

Returns:A string giving the timestamp, in the format:
YYYYMMDDhhmmssZ
YYYYMMDDhhmmss+hhmm
YYYYMMDDhhmmss-hhmm

or None if there is no value set.

get_notBefore()

Retrieve the time stamp for when the certificate starts being valid

Returns:A string giving the timestamp, in the format:
YYYYMMDDhhmmssZ
YYYYMMDDhhmmss+hhmm
YYYYMMDDhhmmss-hhmm

or None if there is no value set.

get_pubkey()

Get the public key of the certificate

Returns:The public key
get_serial_number()

Return serial number of the certificate

Returns:Serial number as a Python integer
get_signature_algorithm()

Retrieve the signature algorithm used in the certificate

Returns:A byte string giving the name of the signature algorithm used in the certificate.
Raises ValueError:
 If the signature algorithm is undefined.
get_subject()

Create an X509Name object for the subject of the certificate

Returns:An X509Name object
get_version()

Return version number of the certificate

Returns:Version number as a Python integer
gmtime_adj_notAfter(amount)

Adjust the time stamp for when the certificate stops being valid

Parameters:amount (int) – The number of seconds by which to adjust the ending validity time.
Returns:None
gmtime_adj_notBefore(amount)

Change the timestamp for when the certificate starts being valid to the current time plus an offset.

Parameters:amount – The number of seconds by which to adjust the starting validity time.
Returns:None
has_expired()

Check whether the certificate has expired.

Returns:True if the certificate has expired, false otherwise
set_issuer(issuer)

Set the issuer of the certificate

Parameters:issuer (X509Name) – The issuer name
Returns:None
set_notAfter(when)

Set the time stamp for when the certificate stops being valid

Parameters:when (bytes) –

A string giving the timestamp, in the format:

YYYYMMDDhhmmssZ YYYYMMDDhhmmss+hhmm YYYYMMDDhhmmss-hhmm

Returns:None
set_notBefore(when)

Set the time stamp for when the certificate starts being valid

Parameters:when (bytes) –

A string giving the timestamp, in the format:

YYYYMMDDhhmmssZ YYYYMMDDhhmmss+hhmm YYYYMMDDhhmmss-hhmm

Returns:None
set_pubkey(pkey)

Set the public key of the certificate

Parameters:pkey – The public key
Returns:None
set_serial_number(serial)

Set serial number of the certificate

Parameters:serial (int) – The serial number
Returns:None
set_subject(subject)

Set the subject of the certificate

Parameters:subject (X509Name) – The subject name
Returns:None
set_version(version)

Set version number of the certificate

Parameters:version (int) – The version number
Returns:None
sign(pkey, digest)

Sign the certificate using the supplied key and digest

Parameters:
  • pkey – The key to sign with
  • digest – The message digest to use
Returns:

None

subject_name_hash()

Return the hash of the X509 subject.

Returns:The hash of the subject.

X509Name objects

class OpenSSL.crypto.X509Name(name)
__init__(name)

Create a new X509Name, copying the given X509Name instance.

Parameters:name – An X509Name object to copy
der()

Return the DER encoding of this name

Returns:A bytes instance giving the DER encoded form of this name.
get_components()

Returns the split-up components of this name.

Returns:List of tuples (name, value).
hash()

Return the hash value of this name

Returns:None

X509Req objects

class OpenSSL.crypto.X509Req
add_extensions(extensions)

Add extensions to the request.

Parameters:extensions – a sequence of X509Extension objects
Returns:None
get_extensions()

Get extensions to the request.

Returns:A list of X509Extension objects.
get_pubkey()

Get the public key from the certificate request

Returns:The public key
get_subject()

Create an X509Name object for the subject of the certificate request

Returns:An X509Name object
get_version()

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

Returns:an integer giving the value of the version subfield
set_pubkey(pkey)

Set the public key of the certificate request

Parameters:pkey – The public key to use
Returns:None
set_version(version)

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

Parameters:version – The version number
Returns:None
sign(pkey, digest)

Sign the certificate request using the supplied key and digest

Parameters:
  • pkey – The key to sign with
  • digest – The message digest to use
Returns:

None

verify(pkey)

Verifies a certificate request using the supplied public key

Parameters:key – a public key
Returns:True if the signature is correct.
Raises OpenSSL.crypto.Error:
 If the signature is invalid or there is a problem verifying the signature.

X509Store objects

class OpenSSL.crypto.X509Store

X509StoreContextError objects

class OpenSSL.crypto.X509StoreContextError(message, certificate)

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, certificate)

An X.509 store context.

An X509StoreContext is used to define some of the criteria for certificate verification. The information encapsulated in this object includes, but is not limited to, a set of trusted certificates, verification parameters, and revoked certificates.

Of these, only the set of trusted certificates is currently exposed.

Variables:
  • _store_ctx – The underlying X509_STORE_CTX structure used by this instance. It is dynamically allocated and automatically garbage collected.
  • _store – See the store __init__ parameter.
  • _cert – See the certificate __init__ parameter.
set_store(store)

Set the context’s trust store.

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

Verify a certificate in a context.

Parameters:store_ctx – The X509StoreContext to verify.
Raises:Error

X509StoreFlags constants

PKey objects

class OpenSSL.crypto.PKey
bits()

Returns the number of bits of the key

Returns:The number of bits of the key.
check()

Check the consistency of an RSA private key.

Returns:

True if key is consistent.

Raises:
  • 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.
generate_key(type, bits)

Generate a key of a given type, with a given number of a bits

Parameters:
  • type – The key type (TYPE_RSA or TYPE_DSA)
  • bits – The number of bits
Returns:

None

type()

Returns the type of the key

Returns:The type of the key.
OpenSSL.crypto.TYPE_RSA
OpenSSL.crypto.TYPE_DSA

Key type constants.

PKCS7 objects

PKCS7 objects have the following methods:

PKCS7.type_is_signed()

FIXME

PKCS7.type_is_enveloped()

FIXME

PKCS7.type_is_signedAndEnveloped()

FIXME

PKCS7.type_is_data()

FIXME

PKCS7.get_type_name()

Get the type name of the PKCS7.

PKCS12 objects

class OpenSSL.crypto.PKCS12
export(passphrase=None, iter=2048, maciter=1)

Dump a PKCS12 object as a string. See also “man PKCS12_create”.

Parameters:
  • passphrase (bytes) – used to encrypt the PKCS12
  • iter (int) – How many times to repeat the encryption
  • maciter (int) – How many times to repeat the MAC
Returns:

The string containing the PKCS12

get_ca_certificates()

Return CA certificates within of the PKCS12 object

Returns:A newly created tuple containing the CA certificates in the chain, if any are present, or None if no CA certificates are present.
get_certificate()

Return certificate portion of the PKCS12 structure

Returns:X509 object containing the certificate
get_friendlyname()

Return friendly name portion of the PKCS12 structure

Returns:String containing the friendlyname
get_privatekey()

Return private key portion of the PKCS12 structure

Returns:PKey object containing the private key
set_ca_certificates(cacerts)

Replace or set the CA certificates within the PKCS12 object.

Parameters:cacerts (None or an iterable of X509) – The new CA certificates.
Returns:None
set_certificate(cert)

Replace the certificate portion of the PKCS12 structure

Parameters:cert (X509 or None) – The new certificate.
Returns:None
set_friendlyname(name)

Replace or set the certificate portion of the PKCS12 structure

Parameters:name (bytes) – The new friendly name.
Returns:None
set_privatekey(pkey)

Replace or set the certificate portion of the PKCS12 structure

Parameters:pkey (PKey) – The new private key.
Returns:None

X509Extension objects

class OpenSSL.crypto.X509Extension(type_name, critical, value, subject=None, issuer=None)
__init__(type_name, critical, value, subject=None, issuer=None)
Parameters:
  • typename (str) – The name of the extension to create.
  • critical – A flag indicating whether this is a critical extension.
  • value (str) – The value of the extension.
  • subject (X509) – Optional X509 cert to use as subject.
  • issuer (X509) – Optional X509 cert to use as issuer.
Returns:

The X509Extension object

__str__()
Returns:a nice text representation of the extension
get_critical()

Returns the critical field of the X509Extension

Returns:The critical field.
get_data()

Returns the data of the X509Extension

Returns:A str giving the X509Extension’s ASN.1 encoded data.
get_short_name()

Returns the short version of the type name of the X509Extension

Returns:The short type name.

NetscapeSPKI objects

class OpenSSL.crypto.NetscapeSPKI
b64_encode()

Generate a base64 encoded string from an SPKI

Returns:The base64 encoded string
get_pubkey()

Get the public key of the certificate

Returns:The public key
set_pubkey(pkey)

Set the public key of the certificate

Parameters:pkey – The public key
Returns:None
sign(pkey, digest)

Sign the certificate request using the supplied key and digest

Parameters:
  • pkey – The key to sign with
  • digest – The message digest to use
Returns:

None

verify(key)

Verifies a certificate request using the supplied public key

Parameters:key – a public key
Returns:True if the signature is correct.
Raises OpenSSL.crypto.Error:
 If the signature is invalid or there is a problem verifying the signature.

CRL objects

class OpenSSL.crypto.CRL
__init__()

Create a new empty CRL object.

add_revoked(revoked)

Add a revoked (by value not reference) to the CRL structure

Parameters:revoked (X509) – The new revoked.
Returns:None
export(cert, key, type=1, days=100, digest=<object object>)

export a CRL as a string

Parameters:
  • cert (X509) – Used to sign CRL.
  • key (PKey) – Used to sign CRL.
  • type – The export format, either FILETYPE_PEM, FILETYPE_ASN1, or FILETYPE_TEXT.
  • days (int) – The number of days until the next update of this CRL.
  • digest (bytes) – The name of the message digest to use (eg b"sha1").
Returns:

bytes

get_revoked()

Return revoked portion of the CRL structure (by value not reference).

Returns:A tuple of Revoked objects.

Revoked objects

class OpenSSL.crypto.Revoked
all_reasons()

Return a list of all the supported reason strings.

Returns:A list of reason strings.
get_reason()

Return the reason of a Revoked object.

Returns:The reason as a string
get_rev_date()

Retrieve the revocation date

Returns:A string giving the timestamp, in the format:

YYYYMMDDhhmmssZ YYYYMMDDhhmmss+hhmm YYYYMMDDhhmmss-hhmm

get_serial()

Return the serial number of a Revoked structure

Returns:The serial number as a string
set_reason(reason)

Set the reason of a Revoked object.

If reason is None, delete the reason instead.

Parameters:reason (str or NoneType) – The reason string.
Returns:None
set_rev_date(when)

Set the revocation timestamp

Parameters:when

A string giving the timestamp, in the format:

YYYYMMDDhhmmssZ YYYYMMDDhhmmss+hhmm YYYYMMDDhhmmss-hhmm

Returns:None
set_serial(hex_str)

Set the serial number of a revoked Revoked structure

Parameters:hex_str (str) – The new serial number.
Returns:None

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