cryptography is a Python library which exposes cryptographic recipes and primitives. Our goal is for it to be your “cryptographic standard library”. If you are interested in learning more about the field of cryptography, we recommend Crypto 101, by Laurens Van Houtven.

Installation

You can install cryptography with pip:

$ pip install cryptography

See Installation for more information.

Why a new crypto library for Python?

If you’ve done cryptographic work in Python before, you’ve probably seen some other libraries in Python, such as M2Crypto, PyCrypto, or PyOpenSSL. In building cryptography we wanted to address a few issues we observed in the existing libraries:

  • Lack of PyPy and Python 3 support.
  • Lack of maintenance.
  • Use of poor implementations of algorithms (i.e. ones with known side-channel attacks).
  • Lack of high level, “Cryptography for humans”, APIs.
  • Absence of algorithms such as AES-GCM and HKDF.
  • Poor introspectability, and thus poor testability.
  • Extremely error prone APIs, and bad defaults.

Layout

cryptography is broadly divided into two levels. One with safe cryptographic recipes, “cryptography for humans” if you will. These are safe and easy to use and don’t require developers to make many decisions.

The other level is low-level cryptographic primitives. These are often dangerous and can be used incorrectly. They require making decisions and having an in-depth knowledge of the cryptographic concepts at work. Because of the potential danger in working at this level, this is referred to as the “hazardous materials” or “hazmat” layer. These live in the cryptography.hazmat package, and their documentation will always contain an admonition at the top.

We recommend using the recipes layer whenever possible, and falling back to the hazmat layer only when necessary.

The recipes layer

Fernet (symmetric encryption)

Fernet guarantees that a message encrypted using it cannot be manipulated or read without the key. Fernet is an implementation of symmetric (also known as “secret key”) authenticated cryptography. Fernet also has support for implementing key rotation via MultiFernet.

class cryptography.fernet.Fernet(key)[source]

This class provides both encryption and decryption facilities.

>>> from cryptography.fernet import Fernet
>>> key = Fernet.generate_key()
>>> f = Fernet(key)
>>> token = f.encrypt(b"my deep dark secret")
>>> token
'...'
>>> f.decrypt(token)
'my deep dark secret'
Parameters:key (bytes) – A URL-safe base64-encoded 32-byte key. This must be kept secret. Anyone with this key is able to create and read messages.
classmethod generate_key()[source]

Generates a fresh fernet key. Keep this some place safe! If you lose it you’ll no longer be able to decrypt messages; if anyone else gains access to it, they’ll be able to decrypt all of your messages, and they’ll also be able forge arbitrary messages that will be authenticated and decrypted.

encrypt(data)[source]
Parameters:data (bytes) – The message you would like to encrypt.
Returns bytes:A secure message that cannot be read or altered without the key. It is URL-safe base64-encoded. This is referred to as a “Fernet token”.
Raises:TypeError – This exception is raised if data is not bytes.

Note

The encrypted message contains the current time when it was generated in plaintext, the time a message was created will therefore be visible to a possible attacker.

decrypt(token, ttl=None)[source]
Parameters:
  • token (bytes) – The Fernet token. This is the result of calling encrypt().
  • ttl (int) – Optionally, the number of seconds old a message may be for it to be valid. If the message is older than ttl seconds (from the time it was originally created) an exception will be raised. If ttl is not provided (or is None), the age of the message is not considered.
Returns bytes:

The original plaintext.

Raises:
  • cryptography.fernet.InvalidToken – If the token is in any way invalid, this exception is raised. A token may be invalid for a number of reasons: it is older than the ttl, it is malformed, or it does not have a valid signature.
  • TypeError – This exception is raised if token is not bytes.
class cryptography.fernet.MultiFernet(fernets)[source]

New in version 0.7.

This class implements key rotation for Fernet. It takes a list of Fernet instances, and implements the same API:

>>> from cryptography.fernet import Fernet, MultiFernet
>>> key1 = Fernet(Fernet.generate_key())
>>> key2 = Fernet(Fernet.generate_key())
>>> f = MultiFernet([key1, key2])
>>> token = f.encrypt(b"Secret message!")
>>> token
'...'
>>> f.decrypt(token)
'Secret message!'

MultiFernet performs all encryption options using the first key in the list provided. MultiFernet attempts to decrypt tokens with each key in turn. A cryptography.fernet.InvalidToken exception is raised if the correct key is not found in the list provided.

Key rotation makes it easy to replace old keys. You can add your new key at the front of the list to start encrypting new messages, and remove old keys as they are no longer needed.

class cryptography.fernet.InvalidToken[source]

See Fernet.decrypt() for more information.

Using passwords with Fernet

It is possible to use passwords with Fernet. To do this, you need to run the password through a key derivation function such as PBKDF2HMAC, bcrypt or Scrypt.

>>> import base64
>>> import os
>>> from cryptography.fernet import Fernet
>>> from cryptography.hazmat.backends import default_backend
>>> from cryptography.hazmat.primitives import hashes
>>> from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
>>> password = b"password"
>>> salt = os.urandom(16)
>>> kdf = PBKDF2HMAC(
...     algorithm=hashes.SHA256(),
...     length=32,
...     salt=salt,
...     iterations=100000,
...     backend=default_backend()
... )
>>> key = base64.urlsafe_b64encode(kdf.derive(password))
>>> f = Fernet(key)
>>> token = f.encrypt(b"Secret message!")
>>> token
'...'
>>> f.decrypt(token)
'Secret message!'

In this scheme, the salt has to be stored in a retrievable location in order to derive the same key from the password in the future.

The iteration count used should be adjusted to be as high as your server can tolerate. A good default is at least 100,000 iterations which is what Django recommended in 2014.

Implementation

Fernet is built on top of a number of standard cryptographic primitives. Specifically it uses:

  • AES in CBC mode with a 128-bit key for encryption; using PKCS7 padding.
  • HMAC using SHA256 for authentication.
  • Initialization vectors are generated using os.urandom().

For complete details consult the specification.

X.509

X.509 is an ITU-T standard for a public key infrastructure. X.509v3 is defined in RFC 5280 (which obsoletes RFC 2459 and RFC 3280). X.509 certificates are commonly used in protocols like TLS.

Tutorial

X.509 certificates are used to authenticate clients and servers. The most common use case is for web servers using HTTPS.

Creating a Certificate Signing Request (CSR)

When obtaining a certificate from a certificate authority (CA), the usual flow is:

  1. You generate a private/public key pair.
  2. You create a request for a certificate, which is signed by your key (to prove that you own that key).
  3. You give your CSR to a CA (but not the private key).
  4. The CA validates that you own the resource (e.g. domain) you want a certificate for.
  5. The CA gives you a certificate, signed by them, which identifies your public key, and the resource you are authenticated for.
  6. You configure your server to use that certificate, combined with your private key, to server traffic.

If you want to obtain a certificate from a typical commercial CA, here’s how. First, you’ll need to generate a private key, we’ll generate an RSA key (these are the most common types of keys on the web right now):

>>> from cryptography.hazmat.backends import default_backend
>>> from cryptography.hazmat.primitives import serialization
>>> from cryptography.hazmat.primitives.asymmetric import rsa
>>> # Generate our key
>>> key = rsa.generate_private_key(
...     public_exponent=65537,
...     key_size=2048,
...     backend=default_backend()
... )
>>> # Write our key to disk for safe keeping
>>> with open("path/to/store/key.pem", "wb") as f:
...     f.write(key.private_bytes(
...         encoding=serialization.Encoding.PEM,
...         format=serialization.PrivateFormat.TraditionalOpenSSL,
...         encryption_algorithm=serialization.BestAvailableEncryption(b"passphrase"),
...     ))

If you’ve already generated a key you can load it with load_pem_private_key().

Next we need to generate a certificate signing request. A typical CSR contains a few details:

  • Information about our public key (including a signature of the entire body).
  • Information about who we are.
  • Information about what domains this certificate is for.
>>> from cryptography import x509
>>> from cryptography.x509.oid import NameOID
>>> from cryptography.hazmat.primitives import hashes
>>> # Generate a CSR
>>> csr = x509.CertificateSigningRequestBuilder().subject_name(x509.Name([
...     # Provide various details about who we are.
...     x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"),
...     x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"CA"),
...     x509.NameAttribute(NameOID.LOCALITY_NAME, u"San Francisco"),
...     x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"My Company"),
...     x509.NameAttribute(NameOID.COMMON_NAME, u"mysite.com"),
... ])).add_extension(
...     x509.SubjectAlternativeName([
...         # Describe what sites we want this certificate for.
...         x509.DNSName(u"mysite.com"),
...         x509.DNSName(u"www.mysite.com"),
...         x509.DNSName(u"subdomain.mysite.com"),
...     ]),
...     critical=False,
... # Sign the CSR with our private key.
... ).sign(key, hashes.SHA256(), default_backend())
>>> # Write our CSR out to disk.
>>> with open("path/to/csr.pem", "wb") as f:
...     f.write(csr.public_bytes(serialization.Encoding.PEM))

Now we can give our CSR to a CA, who will give a certificate to us in return.

Creating a self-signed certificate

While most of the time you want a certificate that has been signed by someone else (i.e. a certificate authority), so that trust is established, sometimes you want to create a self-signed certificate. Self-signed certificates are not issued by a certificate authority, but instead they are signed by the private key corresponding to the public key they embed.

This means that other people don’t trust these certificates, but it also means they can be issued very easily. In general the only use case for a self-signed certificate is local testing, where you don’t need anyone else to trust your certificate.

Like generating a CSR, we start with creating a new private key:

>>> # Generate our key
>>> key = rsa.generate_private_key(
...     public_exponent=65537,
...     key_size=2048,
...     backend=default_backend()
... )
>>> # Write our key to disk for safe keeping
>>> with open("path/to/store/key.pem", "wb") as f:
...     f.write(key.private_bytes(
...         encoding=serialization.Encoding.PEM,
...         format=serialization.PrivateFormat.TraditionalOpenSSL,
...         encryption_algorithm=serialization.BestAvailableEncryption(b"passphrase"),
...     ))

Then we generate the certificate itself:

>>> # Various details about who we are. For a self-signed certificate the
>>> # subject and issuer are always the same.
>>> subject = issuer = x509.Name([
...     x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"),
...     x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"CA"),
...     x509.NameAttribute(NameOID.LOCALITY_NAME, u"San Francisco"),
...     x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"My Company"),
...     x509.NameAttribute(NameOID.COMMON_NAME, u"mysite.com"),
... ])
>>> cert = x509.CertificateBuilder().subject_name(
...     subject
... ).issuer_name(
...     issuer
... ).public_key(
...     key.public_key()
... ).serial_number(
...     x509.random_serial_number()
... ).not_valid_before(
...     datetime.datetime.utcnow()
... ).not_valid_after(
...     # Our certificate will be valid for 10 days
...     datetime.datetime.utcnow() + datetime.timedelta(days=10)
... ).add_extension(
...     x509.SubjectAlternativeName([x509.DNSName(u"localhost")]),
...     critical=False,
... # Sign our certificate with our private key
... ).sign(key, hashes.SHA256(), default_backend())
>>> # Write our certificate out to disk.
>>> with open("path/to/certificate.pem", "wb") as f:
...     f.write(cert.public_bytes(serialization.Encoding.PEM))

And now we have a private key and certificate that can be used for local testing.

X.509 Reference
Loading Certificates
cryptography.x509.load_pem_x509_certificate(data, backend)[source]

New in version 0.7.

Deserialize a certificate from PEM encoded data. PEM certificates are base64 decoded and have delimiters that look like -----BEGIN CERTIFICATE-----.

Parameters:
  • data (bytes) – The PEM encoded certificate data.
  • backend – A backend supporting the X509Backend interface.
Returns:

An instance of Certificate.

>>> from cryptography import x509
>>> from cryptography.hazmat.backends import default_backend
>>> cert = x509.load_pem_x509_certificate(pem_data, default_backend())
>>> cert.serial_number
2
cryptography.x509.load_der_x509_certificate(data, backend)[source]

New in version 0.7.

Deserialize a certificate from DER encoded data. DER is a binary format and is commonly found in files with the .cer extension (although file extensions are not a guarantee of encoding type).

Parameters:
  • data (bytes) – The DER encoded certificate data.
  • backend – A backend supporting the X509Backend interface.
Returns:

An instance of Certificate.

Loading Certificate Revocation Lists
cryptography.x509.load_pem_x509_crl(data, backend)[source]

New in version 1.1.

Deserialize a certificate revocation list (CRL) from PEM encoded data. PEM requests are base64 decoded and have delimiters that look like -----BEGIN X509 CRL-----.

Parameters:
  • data (bytes) – The PEM encoded request data.
  • backend – A backend supporting the X509Backend interface.
Returns:

An instance of CertificateRevocationList.

>>> from cryptography import x509
>>> from cryptography.hazmat.backends import default_backend
>>> from cryptography.hazmat.primitives import hashes
>>> crl = x509.load_pem_x509_crl(pem_crl_data, default_backend())
>>> isinstance(crl.signature_hash_algorithm, hashes.SHA256)
True
cryptography.x509.load_der_x509_crl(data, backend)[source]

New in version 1.1.

Deserialize a certificate revocation list (CRL) from DER encoded data. DER is a binary format.

Parameters:
  • data (bytes) – The DER encoded request data.
  • backend – A backend supporting the X509Backend interface.
Returns:

An instance of CertificateRevocationList.

Loading Certificate Signing Requests
cryptography.x509.load_pem_x509_csr(data, backend)[source]

New in version 0.9.

Deserialize a certificate signing request (CSR) from PEM encoded data. PEM requests are base64 decoded and have delimiters that look like -----BEGIN CERTIFICATE REQUEST-----. This format is also known as PKCS#10.

Parameters:
  • data (bytes) – The PEM encoded request data.
  • backend – A backend supporting the X509Backend interface.
Returns:

An instance of CertificateSigningRequest.

>>> from cryptography import x509
>>> from cryptography.hazmat.backends import default_backend
>>> from cryptography.hazmat.primitives import hashes
>>> csr = x509.load_pem_x509_csr(pem_req_data, default_backend())
>>> isinstance(csr.signature_hash_algorithm, hashes.SHA1)
True
cryptography.x509.load_der_x509_csr(data, backend)[source]

New in version 0.9.

Deserialize a certificate signing request (CSR) from DER encoded data. DER is a binary format and is not commonly used with CSRs.

Parameters:
  • data (bytes) – The DER encoded request data.
  • backend – A backend supporting the X509Backend interface.
Returns:

An instance of CertificateSigningRequest.

X.509 Certificate Object
class cryptography.x509.Certificate[source]

New in version 0.7.

version
Type:Version

The certificate version as an enumeration. Version 3 certificates are the latest version and also the only type you should see in practice.

Raises:cryptography.x509.InvalidVersion – If the version in the certificate is not a known X.509 version.
>>> cert.version
<Version.v3: 2>
fingerprint(algorithm)[source]
Parameters:algorithm – The HashAlgorithm that will be used to generate the fingerprint.
Return bytes:The fingerprint using the supplied hash algorithm, as bytes.
>>> from cryptography.hazmat.primitives import hashes
>>> cert.fingerprint(hashes.SHA256())
'\x86\xd2\x187Gc\xfc\xe7}[+E9\x8d\xb4\x8f\x10\xe5S\xda\x18u\xbe}a\x03\x08[\xac\xa04?'
serial_number
Type:int

The serial as a Python integer.

>>> cert.serial_number
2
public_key()[source]

The public key associated with the certificate.

Returns:RSAPublicKey or DSAPublicKey or EllipticCurvePublicKey
>>> from cryptography.hazmat.primitives.asymmetric import rsa
>>> public_key = cert.public_key()
>>> isinstance(public_key, rsa.RSAPublicKey)
True
not_valid_before
Type:datetime.datetime

A naïve datetime representing the beginning of the validity period for the certificate in UTC. This value is inclusive.

>>> cert.not_valid_before
datetime.datetime(2010, 1, 1, 8, 30)
not_valid_after
Type:datetime.datetime

A naïve datetime representing the end of the validity period for the certificate in UTC. This value is inclusive.

>>> cert.not_valid_after
datetime.datetime(2030, 12, 31, 8, 30)
issuer

New in version 0.8.

Type:Name

The Name of the issuer.

subject

New in version 0.8.

Type:Name

The Name of the subject.

signature_hash_algorithm
Type:HashAlgorithm

Returns the HashAlgorithm which was used in signing this certificate.

>>> from cryptography.hazmat.primitives import hashes
>>> isinstance(cert.signature_hash_algorithm, hashes.SHA256)
True
signature_algorithm_oid

New in version 1.6.

Type:ObjectIdentifier

Returns the ObjectIdentifier of the signature algorithm used to sign the certificate. This will be one of the OIDs from SignatureAlgorithmOID.

>>> cert.signature_algorithm_oid
<ObjectIdentifier(oid=1.2.840.113549.1.1.11, name=sha256WithRSAEncryption)>
extensions
Type:Extensions

The extensions encoded in the certificate.

Raises:
>>> for ext in cert.extensions:
...     print(ext)
<Extension(oid=<ObjectIdentifier(oid=2.5.29.35, name=authorityKeyIdentifier)>, critical=False, value=<AuthorityKeyIdentifier(key_identifier='\xe4}_\xd1\\\x95\x86\x08,\x05\xae\xbeu\xb6e\xa7\xd9]\xa8f', authority_cert_issuer=None, authority_cert_serial_number=None)>)>
<Extension(oid=<ObjectIdentifier(oid=2.5.29.14, name=subjectKeyIdentifier)>, critical=False, value=<SubjectKeyIdentifier(digest='X\x01\x84$\x1b\xbc+R\x94J=\xa5\x10r\x14Q\xf5\xaf:\xc9')>)>
<Extension(oid=<ObjectIdentifier(oid=2.5.29.15, name=keyUsage)>, critical=True, value=<KeyUsage(digital_signature=False, content_commitment=False, key_encipherment=False, data_encipherment=False, key_agreement=False, key_cert_sign=True, crl_sign=True, encipher_only=None, decipher_only=None)>)>
<Extension(oid=<ObjectIdentifier(oid=2.5.29.32, name=certificatePolicies)>, critical=False, value=<CertificatePolicies([<PolicyInformation(policy_identifier=<ObjectIdentifier(oid=2.16.840.1.101.3.2.1.48.1, name=Unknown OID)>, policy_qualifiers=None)>])>)>
<Extension(oid=<ObjectIdentifier(oid=2.5.29.19, name=basicConstraints)>, critical=True, value=<BasicConstraints(ca=True, path_length=None)>)>
signature

New in version 1.2.

Type:bytes

The bytes of the certificate’s signature.

tbs_certificate_bytes

New in version 1.2.

Type:bytes

The DER encoded bytes payload (as defined by RFC 5280) that is hashed and then signed by the private key of the certificate’s issuer. This data may be used to validate a signature, but use extreme caution as certificate validation is a complex problem that involves much more than just signature checks.

public_bytes(encoding)[source]

New in version 1.0.

Parameters:encoding – The Encoding that will be used to serialize the certificate.
Return bytes:The data that can be written to a file or sent over the network to be verified by clients.
X.509 CRL (Certificate Revocation List) Object
class cryptography.x509.CertificateRevocationList[source]

New in version 1.0.

A CertificateRevocationList is an object representing a list of revoked certificates. The object is iterable and will yield the RevokedCertificate objects stored in this CRL.

>>> len(crl)
1
>>> revoked_certificate = crl[0]
>>> type(revoked_certificate)
<class 'cryptography.hazmat.backends.openssl.x509._RevokedCertificate'>
>>> for r in crl:
...     print(r.serial_number)
0
fingerprint(algorithm)[source]
Parameters:algorithm – The HashAlgorithm that will be used to generate the fingerprint.
Return bytes:The fingerprint using the supplied hash algorithm, as bytes.
>>> from cryptography.hazmat.primitives import hashes
>>> crl.fingerprint(hashes.SHA256())
'e\xcf.\xc4:\x83?1\xdc\xf3\xfc\x95\xd7\xb3\x87\xb3\x8e\xf8\xb93!\x87\x07\x9d\x1b\xb4!\xb9\xe4W\xf4\x1f'
signature_hash_algorithm
Type:HashAlgorithm

Returns the HashAlgorithm which was used in signing this CRL.

>>> from cryptography.hazmat.primitives import hashes
>>> isinstance(crl.signature_hash_algorithm, hashes.SHA256)
True
signature_algorithm_oid

New in version 1.6.

Type:ObjectIdentifier

Returns the ObjectIdentifier of the signature algorithm used to sign the CRL. This will be one of the OIDs from SignatureAlgorithmOID.

>>> crl.signature_algorithm_oid
<ObjectIdentifier(oid=1.2.840.113549.1.1.11, name=sha256WithRSAEncryption)>
issuer
Type:Name

The Name of the issuer.

>>> crl.issuer
<Name([<NameAttribute(oid=<ObjectIdentifier(oid=2.5.4.6, name=countryName)>, value=u'US')>, <NameAttribute(oid=<ObjectIdentifier(oid=2.5.4.3, name=commonName)>, value=u'cryptography.io')>])>
next_update
Type:datetime.datetime

A naïve datetime representing when the next update to this CRL is expected.

>>> crl.next_update
datetime.datetime(2016, 1, 1, 0, 0)
last_update
Type:datetime.datetime

A naïve datetime representing when the this CRL was last updated.

>>> crl.last_update
datetime.datetime(2015, 1, 1, 0, 0)
extensions
Type:Extensions

The extensions encoded in the CRL.

signature

New in version 1.2.

Type:bytes

The bytes of the CRL’s signature.

tbs_certlist_bytes

New in version 1.2.

Type:bytes

The DER encoded bytes payload (as defined by RFC 5280) that is hashed and then signed by the private key of the CRL’s issuer. This data may be used to validate a signature, but use extreme caution as CRL validation is a complex problem that involves much more than just signature checks.

public_bytes(encoding)[source]

New in version 1.2.

Parameters:encoding – The Encoding that will be used to serialize the certificate revocation list.
Return bytes:The data that can be written to a file or sent over the network and used as part of a certificate verification process.
X.509 Certificate Builder
class cryptography.x509.CertificateBuilder[source]

New in version 1.0.

>>> from cryptography import x509
>>> from cryptography.hazmat.backends import default_backend
>>> from cryptography.hazmat.primitives import hashes
>>> from cryptography.hazmat.primitives.asymmetric import rsa
>>> from cryptography.x509.oid import NameOID
>>> import datetime
>>> one_day = datetime.timedelta(1, 0, 0)
>>> private_key = rsa.generate_private_key(
...     public_exponent=65537,
...     key_size=2048,
...     backend=default_backend()
... )
>>> public_key = private_key.public_key()
>>> builder = x509.CertificateBuilder()
>>> builder = builder.subject_name(x509.Name([
...     x509.NameAttribute(NameOID.COMMON_NAME, u'cryptography.io'),
... ]))
>>> builder = builder.issuer_name(x509.Name([
...     x509.NameAttribute(NameOID.COMMON_NAME, u'cryptography.io'),
... ]))
>>> builder = builder.not_valid_before(datetime.datetime.today() - one_day)
>>> builder = builder.not_valid_after(datetime.datetime(2018, 8, 2))
>>> builder = builder.serial_number(x509.random_serial_number())
>>> builder = builder.public_key(public_key)
>>> builder = builder.add_extension(
...     x509.SubjectAlternativeName(
...         [x509.DNSName(u'cryptography.io')]
...     ),
...     critical=False
... )
>>> builder = builder.add_extension(
...     x509.BasicConstraints(ca=False, path_length=None), critical=True,
... )
>>> certificate = builder.sign(
...     private_key=private_key, algorithm=hashes.SHA256(),
...     backend=default_backend()
... )
>>> isinstance(certificate, x509.Certificate)
True
issuer_name(name)[source]

Sets the issuer’s distinguished name.

Parameters:name – The Name that describes the issuer (CA).
subject_name(name)[source]

Sets the subject’s distinguished name.

Parameters:name – The Name that describes the subject.
public_key(public_key)[source]

Sets the subject’s public key.

Parameters:public_key – The subject’s public key. This can be one of RSAPublicKey, DSAPublicKey or EllipticCurvePublicKey
serial_number(serial_number)[source]

Sets the certificate’s serial number (an integer). The CA’s policy determines how it attributes serial numbers to certificates. This number must uniquely identify the certificate given the issuer. CABForum Guidelines require entropy in the serial number to provide protection against hash collision attacks. For more information on secure random number generation, see Random number generation.

Parameters:serial_number – Integer number that will be used by the CA to identify this certificate (most notably during certificate revocation checking). Users should consider using random_serial_number() when possible.
not_valid_before(time)[source]

Sets the certificate’s activation time. This is the time from which clients can start trusting the certificate. It may be different from the time at which the certificate was created.

Parameters:time – The datetime.datetime object (in UTC) that marks the activation time for the certificate. The certificate may not be trusted clients if it is used before this time.
not_valid_after(time)[source]

Sets the certificate’s expiration time. This is the time from which clients should no longer trust the certificate. The CA’s policy will determine how long the certificate should remain in use.

Parameters:time – The datetime.datetime object (in UTC) that marks the expiration time for the certificate. The certificate may not be trusted clients if it is used after this time.
add_extension(extension, critical)[source]

Adds an X.509 extension to the certificate.

Parameters:
  • extension – An extension conforming to the ExtensionType interface.
  • critical – Set to True if the extension must be understood and handled by whoever reads the certificate.
sign(private_key, algorithm, backend)[source]

Sign the certificate using the CA’s private key.

Parameters:
Returns:

Certificate

X.509 CSR (Certificate Signing Request) Object
class cryptography.x509.CertificateSigningRequest[source]

New in version 0.9.

public_key()[source]

The public key associated with the request.

Returns:RSAPublicKey or DSAPublicKey or EllipticCurvePublicKey
>>> from cryptography.hazmat.primitives.asymmetric import rsa
>>> public_key = csr.public_key()
>>> isinstance(public_key, rsa.RSAPublicKey)
True
subject
Type:Name

The Name of the subject.

signature_hash_algorithm
Type:HashAlgorithm

Returns the HashAlgorithm which was used in signing this request.

>>> from cryptography.hazmat.primitives import hashes
>>> isinstance(csr.signature_hash_algorithm, hashes.SHA1)
True
signature_algorithm_oid

New in version 1.6.

Type:ObjectIdentifier

Returns the ObjectIdentifier of the signature algorithm used to sign the request. This will be one of the OIDs from SignatureAlgorithmOID.

>>> csr.signature_algorithm_oid
<ObjectIdentifier(oid=1.2.840.113549.1.1.5, name=sha1WithRSAEncryption)>
extensions
Type:Extensions

The extensions encoded in the certificate signing request.

Raises:
public_bytes(encoding)[source]

New in version 1.0.

Parameters:encoding – The Encoding that will be used to serialize the certificate request.
Return bytes:The data that can be written to a file or sent over the network to be signed by the certificate authority.
signature

New in version 1.2.

Type:bytes

The bytes of the certificate signing request’s signature.

tbs_certrequest_bytes

New in version 1.2.

Type:bytes

The DER encoded bytes payload (as defined by RFC 2986) that is hashed and then signed by the private key (corresponding to the public key embedded in the CSR). This data may be used to validate the CSR signature.

is_signature_valid

New in version 1.3.

Returns True if the CSR signature is correct, False otherwise.

X.509 Certificate Revocation List Builder
class cryptography.x509.CertificateRevocationListBuilder[source]

New in version 1.2.

>>> from cryptography import x509
>>> from cryptography.hazmat.backends import default_backend
>>> from cryptography.hazmat.primitives import hashes
>>> from cryptography.hazmat.primitives.asymmetric import rsa
>>> from cryptography.x509.oid import NameOID
>>> import datetime
>>> one_day = datetime.timedelta(1, 0, 0)
>>> private_key = rsa.generate_private_key(
...     public_exponent=65537,
...     key_size=2048,
...     backend=default_backend()
... )
>>> builder = x509.CertificateRevocationListBuilder()
>>> builder = builder.issuer_name(x509.Name([
...     x509.NameAttribute(NameOID.COMMON_NAME, u'cryptography.io CA'),
... ]))
>>> builder = builder.last_update(datetime.datetime.today())
>>> builder = builder.next_update(datetime.datetime.today() + one_day)
>>> revoked_cert = x509.RevokedCertificateBuilder().serial_number(
...     333
... ).revocation_date(
...     datetime.datetime.today()
... ).build(default_backend())
>>> builder = builder.add_revoked_certificate(revoked_cert)
>>> crl = builder.sign(
...     private_key=private_key, algorithm=hashes.SHA256(),
...     backend=default_backend()
... )
>>> len(crl)
1
issuer_name(name)[source]

Sets the issuer’s distinguished name.

Parameters:name – The Name that describes the issuer (CA).
last_update(time)[source]

Sets this CRL’s activation time. This is the time from which clients can start trusting this CRL. It may be different from the time at which this CRL was created. This is also known as the thisUpdate time.

Parameters:time – The datetime.datetime object (in UTC) that marks the activation time for this CRL. The CRL may not be trusted if it is used before this time.
next_update(time)[source]

Sets this CRL’s next update time. This is the time by which a new CRL will be issued. The CA is allowed to issue a new CRL before this date, however clients are not required to check for it.

Parameters:time – The datetime.datetime object (in UTC) that marks the next update time for this CRL.
add_extension(extension, critical)[source]

Adds an X.509 extension to this CRL.

Parameters:
  • extension – An extension with the ExtensionType interface.
  • critical – Set to True if the extension must be understood and handled by whoever reads the CRL.
add_revoked_certificate(revoked_certificate)[source]

Adds a revoked certificate to this CRL.

Parameters:revoked_certificate – An instance of RevokedCertificate. These can be obtained from an existing CRL or created with RevokedCertificateBuilder.
sign(private_key, algorithm, backend)[source]

Sign this CRL using the CA’s private key.

Parameters:
Returns:

CertificateRevocationList

X.509 Revoked Certificate Object
class cryptography.x509.RevokedCertificate[source]

New in version 1.0.

serial_number
Type:int

An integer representing the serial number of the revoked certificate.

>>> revoked_certificate.serial_number
0
revocation_date
Type:datetime.datetime

A naïve datetime representing the date this certificates was revoked.

>>> revoked_certificate.revocation_date
datetime.datetime(2015, 1, 1, 0, 0)
extensions
Type:Extensions

The extensions encoded in the revoked certificate.

>>> for ext in revoked_certificate.extensions:
...     print(ext)
<Extension(oid=<ObjectIdentifier(oid=2.5.29.24, name=invalidityDate)>, critical=False, value=<InvalidityDate(invalidity_date=2015-01-01 00:00:00)>)>
<Extension(oid=<ObjectIdentifier(oid=2.5.29.21, name=cRLReason)>, critical=False, value=<CRLReason(reason=ReasonFlags.key_compromise)>)>
X.509 Revoked Certificate Builder
class cryptography.x509.RevokedCertificateBuilder[source]

This class is used to create RevokedCertificate objects that can be used with the CertificateRevocationListBuilder.

New in version 1.2.

>>> from cryptography import x509
>>> from cryptography.hazmat.backends import default_backend
>>> import datetime
>>> builder = x509.RevokedCertificateBuilder()
>>> builder = builder.revocation_date(datetime.datetime.today())
>>> builder = builder.serial_number(3333)
>>> revoked_certificate = builder.build(default_backend())
>>> isinstance(revoked_certificate, x509.RevokedCertificate)
True
serial_number(serial_number)[source]

Sets the revoked certificate’s serial number.

Parameters:serial_number – Integer number that is used to identify the revoked certificate.
revocation_date(time)[source]

Sets the certificate’s revocation date.

Parameters:time – The datetime.datetime object (in UTC) that marks the revocation time for the certificate.
add_extension(extension, critical)[source]

Adds an X.509 extension to this revoked certificate.

Parameters:
  • extension – An instance of one of the CRL entry extensions.
  • critical – Set to True if the extension must be understood and handled.
build(backend)[source]

Create a revoked certificate object using the provided backend.

Parameters:backend – Backend that will be used to build the revoked certificate. Must support the X509Backend interface.
Returns:RevokedCertificate
X.509 CSR (Certificate Signing Request) Builder Object
class cryptography.x509.CertificateSigningRequestBuilder[source]

New in version 1.0.

>>> from cryptography import x509
>>> from cryptography.hazmat.backends import default_backend
>>> from cryptography.hazmat.primitives import hashes
>>> from cryptography.hazmat.primitives.asymmetric import rsa
>>> from cryptography.x509.oid import NameOID
>>> private_key = rsa.generate_private_key(
...     public_exponent=65537,
...     key_size=2048,
...     backend=default_backend()
... )
>>> builder = x509.CertificateSigningRequestBuilder()
>>> builder = builder.subject_name(x509.Name([
...     x509.NameAttribute(NameOID.COMMON_NAME, u'cryptography.io'),
... ]))
>>> builder = builder.add_extension(
...     x509.BasicConstraints(ca=False, path_length=None), critical=True,
... )
>>> request = builder.sign(
...     private_key, hashes.SHA256(), default_backend()
... )
>>> isinstance(request, x509.CertificateSigningRequest)
True
subject_name(name)[source]
Parameters:name – The Name of the certificate subject.
Returns:A new CertificateSigningRequestBuilder.
add_extension(extension, critical)[source]
Parameters:
  • extension – An extension conforming to the ExtensionType interface.
  • critical – Set to True if the extension must be understood and handled by whoever reads the certificate.
Returns:

A new CertificateSigningRequestBuilder.

sign(private_key, algorithm, backend)[source]
Parameters:
  • backend – Backend that will be used to sign the request. Must support the X509Backend interface.
  • private_key – The RSAPrivateKey, DSAPrivateKey or EllipticCurvePrivateKey that will be used to sign the request. When the request is signed by a certificate authority, the private key’s associated public key will be stored in the resulting certificate.
  • algorithm – The HashAlgorithm that will be used to generate the request signature.
Returns:

A new CertificateSigningRequest.

class cryptography.x509.Name[source]

New in version 0.8.

An X509 Name is an ordered list of attributes. The object is iterable to get every attribute or you can use Name.get_attributes_for_oid() to obtain the specific type you want. Names are sometimes represented as a slash or comma delimited string (e.g. /CN=mydomain.com/O=My Org/C=US or CN=mydomain.com, O=My Org, C=US).

Technically, a Name is a list of sets of attributes, called Relative Distinguished Names or RDNs, although multi-valued RDNs are rarely encountered. The iteration order of values within a multi-valued RDN is undefined. If you need to handle multi-valued RDNs, the rdns property gives access to an ordered list of RelativeDistinguishedName objects.

A Name can be initialized with an iterable of NameAttribute (the common case where each RDN has a single attribute) or an iterable of RelativeDistinguishedName objects (in the rare case of multi-valued RDNs).

>>> len(cert.subject)
3
>>> for attribute in cert.subject:
...     print(attribute)
<NameAttribute(oid=<ObjectIdentifier(oid=2.5.4.6, name=countryName)>, value=u'US')>
<NameAttribute(oid=<ObjectIdentifier(oid=2.5.4.10, name=organizationName)>, value=u'Test Certificates 2011')>
<NameAttribute(oid=<ObjectIdentifier(oid=2.5.4.3, name=commonName)>, value=u'Good CA')>
rdns

New in version 1.6.

Type:list of RelativeDistinguishedName
get_attributes_for_oid(oid)[source]
Parameters:oid – An ObjectIdentifier instance.
Returns:A list of NameAttribute instances that match the OID provided. If nothing matches an empty list will be returned.
>>> cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)
[<NameAttribute(oid=<ObjectIdentifier(oid=2.5.4.3, name=commonName)>, value=u'Good CA')>]
public_bytes(backend)[source]

New in version 1.6.

Parameters:backend – A backend supporting the X509Backend interface.
Return bytes:The DER encoded name.
class cryptography.x509.Version[source]

New in version 0.7.

An enumeration for X.509 versions.

v1

For version 1 X.509 certificates.

v3

For version 3 X.509 certificates.

class cryptography.x509.NameAttribute[source]

New in version 0.8.

An X.509 name consists of a list of RelativeDistinguishedName instances, which consist of a set of NameAttribute instances.

oid
Type:ObjectIdentifier

The attribute OID.

value
Type:text

The value of the attribute.

class cryptography.x509.RelativeDistinguishedName(attributes)[source]

New in version 1.6.

A relative distinguished name is a non-empty set of name attributes. The object is iterable to get every attribute.

get_attributes_for_oid(oid)[source]
Parameters:oid – An ObjectIdentifier instance.
Returns:A list of NameAttribute instances that match the OID provided. The list should contain zero or one values.
class cryptography.x509.ObjectIdentifier[source]

New in version 0.8.

Object identifiers (frequently seen abbreviated as OID) identify the type of a value (see: NameAttribute).

dotted_string
Type:str

The dotted string value of the OID (e.g. "2.5.4.3")

General Name Classes
class cryptography.x509.GeneralName[source]

New in version 0.9.

This is the generic interface that all the following classes are registered against.

class cryptography.x509.RFC822Name(value)[source]

New in version 0.9.

This corresponds to an email address. For example, user@example.com.

value
Type:text
class cryptography.x509.DNSName(value)[source]

New in version 0.9.

This corresponds to a domain name. For example, cryptography.io.

value
Type:text
class cryptography.x509.DirectoryName(value)[source]

New in version 0.9.

This corresponds to a directory name.

value
Type:Name
class cryptography.x509.UniformResourceIdentifier(value)[source]

New in version 0.9.

This corresponds to a uniform resource identifier. For example, https://cryptography.io. The URI is parsed and IDNA decoded (see RFC 5895).

Note

URIs that do not contain :// in them will not be decoded.

value
Type:text
class cryptography.x509.IPAddress(value)[source]

New in version 0.9.

This corresponds to an IP address.

value
Type:IPv4Address, IPv6Address, IPv4Network, or IPv6Network.
class cryptography.x509.RegisteredID(value)[source]

New in version 0.9.

This corresponds to a registered ID.

value
Type:ObjectIdentifier
class cryptography.x509.OtherName(type_id, value)[source]

New in version 1.0.

This corresponds to an otherName. An otherName has a type identifier and a value represented in binary DER format.

type_id
Type:ObjectIdentifier
value
Type:bytes
X.509 Extensions
class cryptography.x509.Extensions[source]

New in version 0.9.

An X.509 Extensions instance is an ordered list of extensions. The object is iterable to get every extension.

get_extension_for_oid(oid)[source]
Parameters:oid – An ObjectIdentifier instance.
Returns:An instance of the extension class.
Raises:cryptography.x509.ExtensionNotFound – If the certificate does not have the extension requested.
>>> from cryptography.x509.oid import ExtensionOID
>>> cert.extensions.get_extension_for_oid(ExtensionOID.BASIC_CONSTRAINTS)
<Extension(oid=<ObjectIdentifier(oid=2.5.29.19, name=basicConstraints)>, critical=True, value=<BasicConstraints(ca=True, path_length=None)>)>
get_extension_for_class(extclass)[source]

New in version 1.1.

Parameters:extclass – An extension class.
Returns:An instance of the extension class.
Raises:cryptography.x509.ExtensionNotFound – If the certificate does not have the extension requested.
>>> from cryptography import x509
>>> cert.extensions.get_extension_for_class(x509.BasicConstraints)
<Extension(oid=<ObjectIdentifier(oid=2.5.29.19, name=basicConstraints)>, critical=True, value=<BasicConstraints(ca=True, path_length=None)>)>
class cryptography.x509.Extension[source]

New in version 0.9.

oid
Type:ObjectIdentifier

One of the ExtensionOID OIDs.

critical
Type:bool

Determines whether a given extension is critical or not. RFC 5280 requires that “A certificate-using system MUST reject the certificate if it encounters a critical extension it does not recognize or a critical extension that contains information that it cannot process”.

value

Returns an instance of the extension type corresponding to the OID.

class cryptography.x509.ExtensionType[source]

New in version 1.0.

This is the interface against which all the following extension types are registered.

class cryptography.x509.KeyUsage(digital_signature, content_commitment, key_encipherment, data_encipherment, key_agreement, key_cert_sign, crl_sign, encipher_only, decipher_only)[source]

New in version 0.9.

The key usage extension defines the purpose of the key contained in the certificate. The usage restriction might be employed when a key that could be used for more than one operation is to be restricted.

oid

New in version 1.0.

Type:ObjectIdentifier

Returns KEY_USAGE.

digital_signature
Type:bool

This purpose is set to true when the subject public key is used for verifying digital signatures, other than signatures on certificates (key_cert_sign) and CRLs (crl_sign).

content_commitment
Type:bool

This purpose is set to true when the subject public key is used for verifying digital signatures, other than signatures on certificates (key_cert_sign) and CRLs (crl_sign). It is used to provide a non-repudiation service that protects against the signing entity falsely denying some action. In the case of later conflict, a reliable third party may determine the authenticity of the signed data. This was called non_repudiation in older revisions of the X.509 specification.

key_encipherment
Type:bool

This purpose is set to true when the subject public key is used for enciphering private or secret keys.

data_encipherment
Type:bool

This purpose is set to true when the subject public key is used for directly enciphering raw user data without the use of an intermediate symmetric cipher.

key_agreement
Type:bool

This purpose is set to true when the subject public key is used for key agreement. For example, when a Diffie-Hellman key is to be used for key management, then this purpose is set to true.

key_cert_sign
Type:bool

This purpose is set to true when the subject public key is used for verifying signatures on public key certificates. If this purpose is set to true then ca must be true in the BasicConstraints extension.

crl_sign
Type:bool

This purpose is set to true when the subject public key is used for verifying signatures on certificate revocation lists.

encipher_only
Type:bool

When this purposes is set to true and the key_agreement purpose is also set, the subject public key may be used only for enciphering data while performing key agreement.

Raises:ValueError – This is raised if accessed when key_agreement is false.
decipher_only
Type:bool

When this purposes is set to true and the key_agreement purpose is also set, the subject public key may be used only for deciphering data while performing key agreement.

Raises:ValueError – This is raised if accessed when key_agreement is false.
class cryptography.x509.BasicConstraints(ca, path_length)[source]

New in version 0.9.

Basic constraints is an X.509 extension type that defines whether a given certificate is allowed to sign additional certificates and what path length restrictions may exist.

oid

New in version 1.0.

Type:ObjectIdentifier

Returns BASIC_CONSTRAINTS.

ca
Type:bool

Whether the certificate can sign certificates.

path_length
Type:int or None

The maximum path length for certificates subordinate to this certificate. This attribute only has meaning if ca is true. If ca is true then a path length of None means there’s no restriction on the number of subordinate CAs in the certificate chain. If it is zero or greater then it defines the maximum length for a subordinate CA’s certificate chain. For example, a path_length of 1 means the certificate can sign a subordinate CA, but the subordinate CA is not allowed to create subordinates with ca set to true.

class cryptography.x509.ExtendedKeyUsage(usages)[source]

New in version 0.9.

This extension indicates one or more purposes for which the certified public key may be used, in addition to or in place of the basic purposes indicated in the key usage extension. The object is iterable to obtain the list of ExtendedKeyUsageOID OIDs present.

Parameters:usages (list) – A list of ExtendedKeyUsageOID OIDs.
oid

New in version 1.0.

Type:ObjectIdentifier

Returns EXTENDED_KEY_USAGE.

class cryptography.x509.OCSPNoCheck[source]

New in version 1.0.

This presence of this extension indicates that an OCSP client can trust a responder for the lifetime of the responder’s certificate. CAs issuing such a certificate should realize that a compromise of the responder’s key is as serious as the compromise of a CA key used to sign CRLs, at least for the validity period of this certificate. CA’s may choose to issue this type of certificate with a very short lifetime and renew it frequently. This extension is only relevant when the certificate is an authorized OCSP responder.

oid

New in version 1.0.

Type:ObjectIdentifier

Returns OCSP_NO_CHECK.

class cryptography.x509.NameConstraints(permitted_subtrees, excluded_subtrees)[source]

New in version 1.0.

The name constraints extension, which only has meaning in a CA certificate, defines a name space within which all subject names in certificates issued beneath the CA certificate must (or must not) be in. For specific details on the way this extension should be processed see RFC 5280.

oid

New in version 1.0.

Type:ObjectIdentifier

Returns NAME_CONSTRAINTS.

permitted_subtrees
Type:list of GeneralName objects or None

The set of permitted name patterns. If a name matches this and an element in excluded_subtrees it is invalid. At least one of permitted_subtrees and excluded_subtrees will be non-None.

excluded_subtrees
Type:list of GeneralName objects or None

Any name matching a restriction in the excluded_subtrees field is invalid regardless of information appearing in the permitted_subtrees. At least one of permitted_subtrees and excluded_subtrees will be non-None.

class cryptography.x509.AuthorityKeyIdentifier(key_identifier, authority_cert_issuer, authority_cert_serial_number)[source]

New in version 0.9.

The authority key identifier extension provides a means of identifying the public key corresponding to the private key used to sign a certificate. This extension is typically used to assist in determining the appropriate certificate chain. For more information about generation and use of this extension see RFC 5280 section 4.2.1.1.

oid

New in version 1.0.

Type:ObjectIdentifier

Returns AUTHORITY_KEY_IDENTIFIER.

key_identifier
Type:bytes

A value derived from the public key used to verify the certificate’s signature.

authority_cert_issuer
Type:Name or None

The Name of the issuer’s issuer.

authority_cert_serial_number
Type:int or None

The serial number of the issuer’s issuer.

classmethod from_issuer_public_key(public_key)[source]

New in version 1.0.

Note

This method should be used if the issuer certificate does not contain a SubjectKeyIdentifier. Otherwise, use from_issuer_subject_key_identifier().

Creates a new AuthorityKeyIdentifier instance using the public key provided to generate the appropriate digest. This should be the issuer’s public key. The resulting object will contain key_identifier, but authority_cert_issuer and authority_cert_serial_number will be None. The generated key_identifier is the SHA1 hash of the subjectPublicKey ASN.1 bit string. This is the first recommendation in RFC 5280 section 4.2.1.2.

Parameters:public_key – One of RSAPublicKey , DSAPublicKey , or EllipticCurvePublicKey.
>>> from cryptography import x509
>>> from cryptography.hazmat.backends import default_backend
>>> issuer_cert = x509.load_pem_x509_certificate(pem_data, default_backend())
>>> x509.AuthorityKeyIdentifier.from_issuer_public_key(issuer_cert.public_key())
<AuthorityKeyIdentifier(key_identifier='X\x01\x84$\x1b\xbc+R\x94J=\xa5\x10r\x14Q\xf5\xaf:\xc9', authority_cert_issuer=None, authority_cert_serial_number=None)>
classmethod from_issuer_subject_key_identifier(ski)[source]

New in version 1.3.

Note

This method should be used if the issuer certificate contains a SubjectKeyIdentifier. Otherwise, use from_issuer_public_key().

Creates a new AuthorityKeyIdentifier instance using the SubjectKeyIdentifier from the issuer certificate. The resulting object will contain key_identifier, but authority_cert_issuer and authority_cert_serial_number will be None.

Parameters:ski – The SubjectKeyIdentifier from the issuer certificate.
>>> from cryptography import x509
>>> from cryptography.hazmat.backends import default_backend
>>> issuer_cert = x509.load_pem_x509_certificate(pem_data, default_backend())
>>> ski = issuer_cert.extensions.get_extension_for_class(x509.SubjectKeyIdentifier)
>>> x509.AuthorityKeyIdentifier.from_issuer_subject_key_identifier(ski)
<AuthorityKeyIdentifier(key_identifier='X\x01\x84$\x1b\xbc+R\x94J=\xa5\x10r\x14Q\xf5\xaf:\xc9', authority_cert_issuer=None, authority_cert_serial_number=None)>
class cryptography.x509.SubjectKeyIdentifier(digest)[source]

New in version 0.9.

The subject key identifier extension provides a means of identifying certificates that contain a particular public key.

oid

New in version 1.0.

Type:ObjectIdentifier

Returns SUBJECT_KEY_IDENTIFIER.

digest
Type:bytes

The binary value of the identifier.

classmethod from_public_key(public_key)[source]

New in version 1.0.

Creates a new SubjectKeyIdentifier instance using the public key provided to generate the appropriate digest. This should be the public key that is in the certificate. The generated digest is the SHA1 hash of the subjectPublicKey ASN.1 bit string. This is the first recommendation in RFC 5280 section 4.2.1.2.

Parameters:public_key – One of RSAPublicKey , DSAPublicKey , or EllipticCurvePublicKey.
>>> from cryptography import x509
>>> from cryptography.hazmat.backends import default_backend
>>> csr = x509.load_pem_x509_csr(pem_req_data, default_backend())
>>> x509.SubjectKeyIdentifier.from_public_key(csr.public_key())
<SubjectKeyIdentifier(digest='\xdb\xaa\xf0\x06\x11\xdbD\xfe\xbf\x93\x03\x8av\x88WP7\xa6\x91\xf7')>
class cryptography.x509.SubjectAlternativeName(general_names)[source]

New in version 0.9.

Subject alternative name is an X.509 extension that provides a list of general name instances that provide a set of identities for which the certificate is valid. The object is iterable to get every element.

Parameters:general_names (list) – A list of GeneralName instances.
oid

New in version 1.0.

Type:ObjectIdentifier

Returns SUBJECT_ALTERNATIVE_NAME.

get_values_for_type(type)[source]
Parameters:type – A GeneralName instance. This is one of the general name classes.
Returns:A list of values extracted from the matched general names. The type of the returned values depends on the GeneralName.
>>> from cryptography import x509
>>> from cryptography.hazmat.backends import default_backend
>>> from cryptography.hazmat.primitives import hashes
>>> cert = x509.load_pem_x509_certificate(cryptography_cert_pem, default_backend())
>>> # Get the subjectAltName extension from the certificate
>>> ext = cert.extensions.get_extension_for_oid(ExtensionOID.SUBJECT_ALTERNATIVE_NAME)
>>> # Get the dNSName entries from the SAN extension
>>> ext.value.get_values_for_type(x509.DNSName)
[u'www.cryptography.io', u'cryptography.io']
class cryptography.x509.IssuerAlternativeName(general_names)[source]

New in version 1.0.

Issuer alternative name is an X.509 extension that provides a list of general name instances that provide a set of identities for the certificate issuer. The object is iterable to get every element.

Parameters:general_names (list) – A list of GeneralName instances.
oid

New in version 1.0.

Type:ObjectIdentifier

Returns ISSUER_ALTERNATIVE_NAME.

get_values_for_type(type)[source]
Parameters:type – A GeneralName instance. This is one of the general name classes.
Returns:A list of values extracted from the matched general names.
class cryptography.x509.AuthorityInformationAccess(descriptions)[source]

New in version 0.9.

The authority information access extension indicates how to access information and services for the issuer of the certificate in which the extension appears. Information and services may include online validation services (such as OCSP) and issuer data. It is an iterable, containing one or more AccessDescription instances.

Parameters:descriptions (list) – A list of AccessDescription objects.
oid

New in version 1.0.

Type:ObjectIdentifier

Returns AUTHORITY_INFORMATION_ACCESS.

class cryptography.x509.AccessDescription(access_method, access_location)[source]

New in version 0.9.

access_method
Type:ObjectIdentifier

The access method defines what the access_location means. It must be either OCSP or CA_ISSUERS. If it is OCSP the access location will be where to obtain OCSP information for the certificate. If it is CA_ISSUERS the access location will provide additional information about the issuing certificate.

access_location
Type:GeneralName

Where to access the information defined by the access method.

class cryptography.x509.CRLDistributionPoints(distribution_points)[source]

New in version 0.9.

The CRL distribution points extension identifies how CRL information is obtained. It is an iterable, containing one or more DistributionPoint instances.

Parameters:distribution_points (list) – A list of DistributionPoint instances.
oid

New in version 1.0.

Type:ObjectIdentifier

Returns CRL_DISTRIBUTION_POINTS.

class cryptography.x509.DistributionPoint(full_name, relative_name, reasons, crl_issuer)[source]

New in version 0.9.

full_name
Type:list of GeneralName instances or None

This field describes methods to retrieve the CRL. At most one of full_name or relative_name will be non-None.

relative_name
Type:RelativeDistinguishedName or None

This field describes methods to retrieve the CRL relative to the CRL issuer. At most one of full_name or relative_name will be non-None.

Changed in version 1.6: Changed from Name to RelativeDistinguishedName.

crl_issuer
Type:list of GeneralName instances or None

Information about the issuer of the CRL.

reasons
Type:frozenset of ReasonFlags or None

The reasons a given distribution point may be used for when performing revocation checks.

class cryptography.x509.ReasonFlags[source]

New in version 0.9.

An enumeration for CRL reasons.

unspecified

It is unspecified why the certificate was revoked. This reason cannot be used as a reason flag in a DistributionPoint.

key_compromise

This reason indicates that the private key was compromised.

ca_compromise

This reason indicates that the CA issuing the certificate was compromised.

affiliation_changed

This reason indicates that the subject’s name or other information has changed.

superseded

This reason indicates that a certificate has been superseded.

cessation_of_operation

This reason indicates that the certificate is no longer required.

certificate_hold

This reason indicates that the certificate is on hold.

privilege_withdrawn

This reason indicates that the privilege granted by this certificate have been withdrawn.

aa_compromise

When an attribute authority has been compromised.

remove_from_crl

This reason indicates that the certificate was on hold and should be removed from the CRL. This reason cannot be used as a reason flag in a DistributionPoint.

class cryptography.x509.InhibitAnyPolicy(skip_certs)[source]

New in version 1.0.

The inhibit anyPolicy extension indicates that the special OID ANY_POLICY, is not considered an explicit match for other CertificatePolicies except when it appears in an intermediate self-issued CA certificate. The value indicates the number of additional non-self-issued certificates that may appear in the path before ANY_POLICY is no longer permitted. For example, a value of one indicates that ANY_POLICY may be processed in certificates issued by the subject of this certificate, but not in additional certificates in the path.

oid

New in version 1.0.

Type:ObjectIdentifier

Returns INHIBIT_ANY_POLICY.

skip_certs
Type:int
class cryptography.x509.PolicyConstraints[source]

New in version 1.3.

The policy constraints extension is used to inhibit policy mapping or require that each certificate in a chain contain an acceptable policy identifier. For more information about the use of this extension see RFC 5280.

oid
Type:ObjectIdentifier

Returns POLICY_CONSTRAINTS.

require_explicit_policy
Type:int or None

If this field is not None, the value indicates the number of additional certificates that may appear in the chain before an explicit policy is required for the entire path. When an explicit policy is required, it is necessary for all certificates in the chain to contain an acceptable policy identifier in the certificate policies extension. An acceptable policy identifier is the identifier of a policy required by the user of the certification path or the identifier of a policy that has been declared equivalent through policy mapping.

inhibit_policy_mapping
Type:int or None

If this field is not None, the value indicates the number of additional certificates that may appear in the chain before policy mapping is no longer permitted. For example, a value of one indicates that policy mapping may be processed in certificates issued by the subject of this certificate, but not in additional certificates in the chain.

class cryptography.x509.CRLNumber(crl_number)[source]

New in version 1.2.

The CRL number is a CRL extension that conveys a monotonically increasing sequence number for a given CRL scope and CRL issuer. This extension allows users to easily determine when a particular CRL supersedes another CRL. RFC 5280 requires that this extension be present in conforming CRLs.

oid
Type:ObjectIdentifier

Returns CRL_NUMBER.

crl_number
Type:int
class cryptography.x509.UnrecognizedExtension[source]

New in version 1.2.

A generic extension class used to hold the raw value of non-critical extensions that cryptography does not know how to parse. Extensions marked critical will raise UnsupportedExtension.

oid
Type:ObjectIdentifier

Returns the OID associated with this extension.

value
Type:byte

Returns the DER encoded bytes payload of the extension.

class cryptography.x509.CertificatePolicies(policies)[source]

New in version 0.9.

The certificate policies extension is an iterable, containing one or more PolicyInformation instances.

Parameters:policies (list) – A list of PolicyInformation instances.
oid

New in version 1.0.

Type:ObjectIdentifier

Returns CERTIFICATE_POLICIES.

Certificate Policies Classes

These classes may be present within a CertificatePolicies instance.

class cryptography.x509.PolicyInformation(policy_identifier, policy_qualifiers)[source]

New in version 0.9.

Contains a policy identifier and an optional list of qualifiers.

policy_identifier
Type:ObjectIdentifier
policy_qualifiers
Type:list

A list consisting of text and/or UserNotice objects. If the value is text it is a pointer to the practice statement published by the certificate authority. If it is a user notice it is meant for display to the relying party when the certificate is used.

class cryptography.x509.UserNotice(notice_reference, explicit_text)[source]

New in version 0.9.

User notices are intended for display to a relying party when a certificate is used. In practice, few if any UIs expose this data and it is a rarely encoded component.

notice_reference
Type:NoticeReference or None

The notice reference field names an organization and identifies, by number, a particular statement prepared by that organization.

explicit_text

This field includes an arbitrary textual statement directly in the certificate.

Type:text
class cryptography.x509.NoticeReference(organization, notice_numbers)[source]

Notice reference can name an organization and provide information about notices related to the certificate. For example, it might identify the organization name and notice number 1. Application software could have a notice file containing the current set of notices for the named organization; the application would then extract the notice text from the file and display it. In practice this is rarely seen.

New in version 0.9.

organization
Type:text
notice_numbers
Type:list

A list of integers.

CRL Entry Extensions

These extensions are only valid within a RevokedCertificate object.

class cryptography.x509.CertificateIssuer(general_names)[source]

New in version 1.2.

The certificate issuer is an extension that is only valid inside RevokedCertificate objects. If the indirectCRL property of the parent CRL’s IssuingDistributionPoint extension is set, then this extension identifies the certificate issuer associated with the revoked certificate. The object is iterable to get every element.

Parameters:general_names (list) – A list of GeneralName instances.
oid
Type:ObjectIdentifier

Returns CERTIFICATE_ISSUER.

get_values_for_type(type)[source]
Parameters:type – A GeneralName instance. This is one of the general name classes.
Returns:A list of values extracted from the matched general names. The type of the returned values depends on the GeneralName.
class cryptography.x509.CRLReason(reason)[source]

New in version 1.2.

CRL reason (also known as reasonCode) is an extension that is only valid inside RevokedCertificate objects. It identifies a reason for the certificate revocation.

Parameters:reason – A value from the CRLEntryExtensionOID enum.
oid
Type:ObjectIdentifier

Returns CRL_REASON.

reason
Type:An element from ReasonFlags
class cryptography.x509.InvalidityDate(invalidity_date)[source]

New in version 1.2.

Invalidity date is an extension that is only valid inside RevokedCertificate objects. It provides the date on which it is known or suspected that the private key was compromised or that the certificate otherwise became invalid. This date may be earlier than the revocation date in the CRL entry, which is the date at which the CA processed the revocation.

Parameters:invalidity_date – The datetime.datetime when it is known or suspected that the private key was compromised.
oid
Type:ObjectIdentifier

Returns INVALIDITY_DATE.

invalidity_date
Type:datetime.datetime
Object Identifiers

X.509 elements are frequently identified by ObjectIdentifier instances. The following common OIDs are available as constants.

class cryptography.x509.oid.NameOID[source]

These OIDs are typically seen in X.509 names.

New in version 1.0.

COMMON_NAME

Corresponds to the dotted string "2.5.4.3". Historically the domain name would be encoded here for server certificates. RFC 2818 deprecates this practice and names of that type should now be located in a SubjectAlternativeName extension.

COUNTRY_NAME

Corresponds to the dotted string "2.5.4.6".

LOCALITY_NAME

Corresponds to the dotted string "2.5.4.7".

STATE_OR_PROVINCE_NAME

Corresponds to the dotted string "2.5.4.8".

STREET_ADDRESS

New in version 1.6.

Corresponds to the dotted string "2.5.4.9".

ORGANIZATION_NAME

Corresponds to the dotted string "2.5.4.10".

ORGANIZATIONAL_UNIT_NAME

Corresponds to the dotted string "2.5.4.11".

SERIAL_NUMBER

Corresponds to the dotted string "2.5.4.5". This is distinct from the serial number of the certificate itself (which can be obtained with serial_number()).

SURNAME

Corresponds to the dotted string "2.5.4.4".

GIVEN_NAME

Corresponds to the dotted string "2.5.4.42".

TITLE

Corresponds to the dotted string "2.5.4.12".

GENERATION_QUALIFIER

Corresponds to the dotted string "2.5.4.44".

X500_UNIQUE_IDENTIFIER

New in version 1.6.

Corresponds to the dotted string "2.5.4.45".

DN_QUALIFIER

Corresponds to the dotted string "2.5.4.46". This specifies disambiguating information to add to the relative distinguished name of an entry. See RFC 2256.

PSEUDONYM

Corresponds to the dotted string "2.5.4.65".

USER_ID

New in version 1.6.

Corresponds to the dotted string "0.9.2342.19200300.100.1.1".

DOMAIN_COMPONENT

Corresponds to the dotted string "0.9.2342.19200300.100.1.25". A string holding one component of a domain name. See RFC 4519.

EMAIL_ADDRESS

Corresponds to the dotted string "1.2.840.113549.1.9.1".

JURISDICTION_COUNTRY_NAME

Corresponds to the dotted string "1.3.6.1.4.1.311.60.2.1.3".

JURISDICTION_LOCALITY_NAME

Corresponds to the dotted string "1.3.6.1.4.1.311.60.2.1.1".

JURISDICTION_STATE_OR_PROVINCE_NAME

Corresponds to the dotted string "1.3.6.1.4.1.311.60.2.1.2".

BUSINESS_CATEGORY

Corresponds to the dotted string "2.5.4.15".

POSTAL_ADDRESS

New in version 1.6.

Corresponds to the dotted string "2.5.4.16".

POSTAL_CODE

New in version 1.6.

Corresponds to the dotted string "2.5.4.17".

class cryptography.x509.oid.SignatureAlgorithmOID[source]

New in version 1.0.

RSA_WITH_MD5

Corresponds to the dotted string "1.2.840.113549.1.1.4". This is an MD5 digest signed by an RSA key.

RSA_WITH_SHA1

Corresponds to the dotted string "1.2.840.113549.1.1.5". This is a SHA1 digest signed by an RSA key.

RSA_WITH_SHA224

Corresponds to the dotted string "1.2.840.113549.1.1.14". This is a SHA224 digest signed by an RSA key.

RSA_WITH_SHA256

Corresponds to the dotted string "1.2.840.113549.1.1.11". This is a SHA256 digest signed by an RSA key.

RSA_WITH_SHA384

Corresponds to the dotted string "1.2.840.113549.1.1.12". This is a SHA384 digest signed by an RSA key.

RSA_WITH_SHA512

Corresponds to the dotted string "1.2.840.113549.1.1.13". This is a SHA512 digest signed by an RSA key.

ECDSA_WITH_SHA1

Corresponds to the dotted string "1.2.840.10045.4.1". This is a SHA1 digest signed by an ECDSA key.

ECDSA_WITH_SHA224

Corresponds to the dotted string "1.2.840.10045.4.3.1". This is a SHA224 digest signed by an ECDSA key.

ECDSA_WITH_SHA256

Corresponds to the dotted string "1.2.840.10045.4.3.2". This is a SHA256 digest signed by an ECDSA key.

ECDSA_WITH_SHA384

Corresponds to the dotted string "1.2.840.10045.4.3.3". This is a SHA384 digest signed by an ECDSA key.

ECDSA_WITH_SHA512

Corresponds to the dotted string "1.2.840.10045.4.3.4". This is a SHA512 digest signed by an ECDSA key.

DSA_WITH_SHA1

Corresponds to the dotted string "1.2.840.10040.4.3". This is a SHA1 digest signed by a DSA key.

DSA_WITH_SHA224

Corresponds to the dotted string "2.16.840.1.101.3.4.3.1". This is a SHA224 digest signed by a DSA key.

DSA_WITH_SHA256

Corresponds to the dotted string "2.16.840.1.101.3.4.3.2". This is a SHA256 digest signed by a DSA key.

class cryptography.x509.oid.ExtendedKeyUsageOID[source]

New in version 1.0.

SERVER_AUTH

Corresponds to the dotted string "1.3.6.1.5.5.7.3.1". This is used to denote that a certificate may be used for TLS web server authentication.

CLIENT_AUTH

Corresponds to the dotted string "1.3.6.1.5.5.7.3.2". This is used to denote that a certificate may be used for TLS web client authentication.

CODE_SIGNING

Corresponds to the dotted string "1.3.6.1.5.5.7.3.3". This is used to denote that a certificate may be used for code signing.

EMAIL_PROTECTION

Corresponds to the dotted string "1.3.6.1.5.5.7.3.4". This is used to denote that a certificate may be used for email protection.

TIME_STAMPING

Corresponds to the dotted string "1.3.6.1.5.5.7.3.8". This is used to denote that a certificate may be used for time stamping.

OCSP_SIGNING

Corresponds to the dotted string "1.3.6.1.5.5.7.3.9". This is used to denote that a certificate may be used for signing OCSP responses.

class cryptography.x509.oid.AuthorityInformationAccessOID[source]

New in version 1.0.

OCSP

Corresponds to the dotted string "1.3.6.1.5.5.7.48.1". Used as the identifier for OCSP data in AccessDescription objects.

CA_ISSUERS

Corresponds to the dotted string "1.3.6.1.5.5.7.48.2". Used as the identifier for CA issuer data in AccessDescription objects.

class cryptography.x509.oid.CertificatePoliciesOID[source]

New in version 1.0.

CPS_QUALIFIER

Corresponds to the dotted string "1.3.6.1.5.5.7.2.1".

CPS_USER_NOTICE

Corresponds to the dotted string "1.3.6.1.5.5.7.2.2".

ANY_POLICY

Corresponds to the dotted string "2.5.29.32.0".

class cryptography.x509.oid.ExtensionOID[source]

New in version 1.0.

BASIC_CONSTRAINTS

Corresponds to the dotted string "2.5.29.19". The identifier for the BasicConstraints extension type.

KEY_USAGE

Corresponds to the dotted string "2.5.29.15". The identifier for the KeyUsage extension type.

SUBJECT_ALTERNATIVE_NAME

Corresponds to the dotted string "2.5.29.17". The identifier for the SubjectAlternativeName extension type.

ISSUER_ALTERNATIVE_NAME

Corresponds to the dotted string "2.5.29.18". The identifier for the IssuerAlternativeName extension type.

SUBJECT_KEY_IDENTIFIER

Corresponds to the dotted string "2.5.29.14". The identifier for the SubjectKeyIdentifier extension type.

NAME_CONSTRAINTS

Corresponds to the dotted string "2.5.29.30". The identifier for the NameConstraints extension type.

CRL_DISTRIBUTION_POINTS

Corresponds to the dotted string "2.5.29.31". The identifier for the CRLDistributionPoints extension type.

CERTIFICATE_POLICIES

Corresponds to the dotted string "2.5.29.32". The identifier for the CertificatePolicies extension type.

AUTHORITY_KEY_IDENTIFIER

Corresponds to the dotted string "2.5.29.35". The identifier for the AuthorityKeyIdentifier extension type.

EXTENDED_KEY_USAGE

Corresponds to the dotted string "2.5.29.37". The identifier for the ExtendedKeyUsage extension type.

AUTHORITY_INFORMATION_ACCESS

Corresponds to the dotted string "1.3.6.1.5.5.7.1.1". The identifier for the AuthorityInformationAccess extension type.

INHIBIT_ANY_POLICY

Corresponds to the dotted string "2.5.29.54". The identifier for the InhibitAnyPolicy extension type.

OCSP_NO_CHECK

Corresponds to the dotted string "1.3.6.1.5.5.7.48.1.5". The identifier for the OCSPNoCheck extension type.

CRL_NUMBER

Corresponds to the dotted string "2.5.29.20". The identifier for the CRLNumber extension type. This extension only has meaning for certificate revocation lists.

POLICY_CONSTRAINTS

Corresponds to the dotted string "2.5.29.36". The identifier for the PolicyConstraints extension type.

class cryptography.x509.oid.CRLEntryExtensionOID[source]

New in version 1.2.

CERTIFICATE_ISSUER

Corresponds to the dotted string "2.5.29.29".

CRL_REASON

Corresponds to the dotted string "2.5.29.21".

INVALIDITY_DATE

Corresponds to the dotted string "2.5.29.24".

Helper Functions
cryptography.x509.random_serial_number()[source]

New in version 1.6.

Generates a random serial number suitable for use when constructing certificates.

Exceptions
class cryptography.x509.InvalidVersion[source]

This is raised when an X.509 certificate has an invalid version number.

parsed_version
Type:int

Returns the raw version that was parsed from the certificate.

class cryptography.x509.DuplicateExtension[source]

This is raised when more than one X.509 extension of the same type is found within a certificate.

oid
Type:ObjectIdentifier

Returns the OID.

class cryptography.x509.UnsupportedExtension[source]

This is raised when a certificate contains an unsupported extension type that is marked critical.

oid
Type:ObjectIdentifier

Returns the OID.

class cryptography.x509.ExtensionNotFound[source]

This is raised when calling Extensions.get_extension_for_oid() with an extension OID that is not present in the certificate.

oid
Type:ObjectIdentifier

Returns the OID.

class cryptography.x509.UnsupportedGeneralNameType[source]

This is raised when a certificate contains an unsupported general name type in an extension.

type
Type:int

The integer value of the unsupported type. The complete list of types can be found in RFC 5280 section 4.2.1.6.

Random number generation

When generating random data for use in cryptographic operations, such as an initialization vector for encryption in CBC mode, you do not want to use the standard random module APIs. This is because they do not provide a cryptographically secure random number generator, which can result in major security issues depending on the algorithms in use.

Therefore, it is our recommendation to always use your operating system’s provided random number generator, which is available as os.urandom(). For example, if you need 16 bytes of random data for an initialization vector, you can obtain them with:

>>> import os
>>> iv = os.urandom(16)

This will use /dev/urandom on UNIX platforms, and CryptGenRandom on Windows.

If you need your random number as an integer (for example, for serial_number()), you can use int.from_bytes to convert the result of os.urandom:

>>> serial = int.from_bytes(os.urandom(20), byteorder="big")

Exceptions

class cryptography.exceptions.UnsupportedAlgorithm[source]

Raised when the requested algorithm, or combination of algorithms is not supported.

class cryptography.exceptions.AlreadyFinalized[source]

This is raised when a context is used after being finalized.

class cryptography.exceptions.InvalidSignature[source]

This is raised when signature verification fails. This can occur with HMAC or asymmetric key signature validation.

class cryptography.exceptions.NotYetFinalized[source]

This is raised when the AEAD tag property is accessed on a context before it is finalized.

class cryptography.exceptions.AlreadyUpdated[source]

This is raised when additional data is added to a context after update has already been called.

class cryptography.exceptions.InvalidKey[source]

This is raised when the verify method of a key derivation function’s computed key does not match the expected key.

Frequently asked questions

How does cryptography compare to NaCl (Networking and Cryptography Library)?

While cryptography and NaCl both share the goal of making cryptography easier, and safer, to use for developers, cryptography is designed to be a general purpose library, interoperable with existing systems, while NaCl features a collection of hand selected algorithms.

cryptography‘s recipes layer has similar goals to NaCl.

If you prefer NaCl’s design, we highly recommend PyNaCl.

Compiling cryptography on OS X produces a fatal error: 'openssl/aes.h' file not found error

This happens because OS X 10.11 no longer includes a copy of OpenSSL. cryptography now provides wheels which include a statically linked copy of OpenSSL. You’re seeing this error because your copy of pip is too old to find our wheel files. Upgrade your copy of pip with pip install -U pip and then try install cryptography again.

Starting cryptography using mod_wsgi produces an InternalError during a call in _register_osrandom_engine

Upgrade to the latest cryptography and this issue should be resolved.

cryptography raised an InternalError and I’m not sure what to do?

Frequently InternalError is raised when there are errors on the OpenSSL error stack that were placed there by other libraries that are also using OpenSSL. Try removing the other libraries and see if the problem persists. If you have no other libraries using OpenSSL in your process, or they do not appear to be at fault, it’s possible that this is a bug in cryptography. Please file an issue with instructions on how to reproduce it.

Installing cryptography fails with ImportError: No module named setuptools_ext

Your cffi package is out of date. pip install -U cffi to update it.

Installing cryptography with OpenSSL 0.9.8 or 1.0.0 fails

The OpenSSL project has dropped support for the 0.9.8 and 1.0.0 release series. Since they are no longer receiving security patches from upstream, cryptography is also dropping support for them. To fix this issue you should upgrade to a newer version of OpenSSL (1.0.1 or later). This may require you to upgrade to a newer operating system.

Glossary

authentication
The process of verifying that a message was created by a specific individual (or program). Like encryption, authentication can be either symmetric or asymmetric. Authentication is necessary for effective encryption.
ciphertext
The encoded data, it’s not user readable. Potential attackers are able to see this.
ciphertext indistinguishability
This is a property of encryption systems whereby two encrypted messages aren’t distinguishable without knowing the encryption key. This is considered a basic, necessary property for a working encryption system.
decryption
The process of converting ciphertext to plaintext.
encryption
The process of converting plaintext to ciphertext.
key
Secret data is encoded with a function using this key. Sometimes multiple keys are used. These must be kept secret, if a key is exposed to an attacker, any data encrypted with it will be exposed.
nonce
A nonce is a number used once. Nonces are used in many cryptographic protocols. Generally, a nonce does not have to be secret or unpredictable, but it must be unique. A nonce is often a random or pseudo-random number (see Random number generation). Since a nonce does not have to be unpredictable, it can also take a form of a counter.
plaintext
User-readable data you care about.
private key
This is one of two keys involved in public-key cryptography. It can be used to decrypt messages which were encrypted with the corresponding public key, as well as to create signatures, which can be verified with the corresponding public key. These must be kept secret, if they are exposed, all encrypted messages are compromised, and an attacker will be able to forge signatures.
public key
This is one of two keys involved in public-key cryptography. It can be used to encrypt messages for someone possessing the corresponding private key and to verify signatures created with the corresponding private key. This can be distributed publicly, hence the name.
public-key cryptography
asymmetric cryptography
Cryptographic operations where encryption and decryption use different keys. There are separate encryption and decryption keys. Typically encryption is performed using a public key, and it can then be decrypted using a private key. Asymmetric cryptography can also be used to create signatures, which can be generated with a private key and verified with a public key.
symmetric cryptography
Cryptographic operations where encryption and decryption use the same key.
text
This type corresponds to unicode on Python 2 and str on Python 3. This is equivalent to six.text_type.

The hazardous materials layer

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.

Primitives

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.

Message digests
class cryptography.hazmat.primitives.hashes.Hash(algorithm, backend)[source]

A cryptographic hash function takes an arbitrary block of data and calculates a fixed-size bit string (a digest), such that different data results (with a high probability) in different digests.

This is an implementation of HashContext meant to be used with HashAlgorithm implementations to provide an incremental interface to calculating various message digests.

>>> from cryptography.hazmat.backends import default_backend
>>> from cryptography.hazmat.primitives import hashes
>>> digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
>>> digest.update(b"abc")
>>> digest.update(b"123")
>>> digest.finalize()
'l\xa1=R\xcap\xc8\x83\xe0\xf0\xbb\x10\x1eBZ\x89\xe8bM\xe5\x1d\xb2\xd29%\x93\xafj\x84\x11\x80\x90'

If the backend doesn’t support the requested algorithm an UnsupportedAlgorithm exception will be raised.

Keep in mind that attacks against cryptographic hashes only get stronger with time, and that often algorithms that were once thought to be strong, become broken. Because of this it’s important to include a plan for upgrading the hash algorithm you use over time. For more information, see Lifetimes of cryptographic hash functions.

Parameters:
Raises:

cryptography.exceptions.UnsupportedAlgorithm – This is raised if the provided backend does not implement HashBackend

update(data)[source]
Parameters:

data (bytes) – The bytes to be hashed.

Raises:
copy()[source]

Copy this Hash instance, usually so that you may call finalize() to get an intermediate digest value while we continue to call update() on the original instance.

Returns:A new instance of Hash that can be updated and finalized independently of the original instance.
Raises:cryptography.exceptions.AlreadyFinalized – See finalize().
finalize()[source]

Finalize the current context and return the message digest as bytes.

After finalize has been called this object can no longer be used and update(), copy(), and finalize() will raise an AlreadyFinalized exception.

Return bytes:The message digest as bytes.
SHA-2 family
class cryptography.hazmat.primitives.hashes.SHA224[source]

SHA-224 is a cryptographic hash function from the SHA-2 family and is standardized by NIST. It produces a 224-bit message digest.

class cryptography.hazmat.primitives.hashes.SHA256[source]

SHA-256 is a cryptographic hash function from the SHA-2 family and is standardized by NIST. It produces a 256-bit message digest.

class cryptography.hazmat.primitives.hashes.SHA384[source]

SHA-384 is a cryptographic hash function from the SHA-2 family and is standardized by NIST. It produces a 384-bit message digest.

class cryptography.hazmat.primitives.hashes.SHA512[source]

SHA-512 is a cryptographic hash function from the SHA-2 family and is standardized by NIST. It produces a 512-bit message digest.

BLAKE2

BLAKE2 is a cryptographic hash function specified in RFC 7693. BLAKE2’s design makes it immune to length-extension attacks, an advantage over the SHA-family of hashes.

Note

While the RFC specifies keying, personalization, and salting features, these are not supported at this time due to limitations in OpenSSL 1.1.0.

class cryptography.hazmat.primitives.hashes.BLAKE2b(digest_size)[source]

BLAKE2b is optimized for 64-bit platforms and produces an 1 to 64-byte message digest.

Parameters:digest_size (int) – The desired size of the hash output in bytes. Only 64 is supported at this time.
Raises:ValueError – If the digest_size is invalid.
class cryptography.hazmat.primitives.hashes.BLAKE2s(digest_size)[source]

BLAKE2s is optimized for 8 to 32-bit platforms and produces a 1 to 32-byte message digest.

Parameters:digest_size (int) – The desired size of the hash output in bytes. Only 32 is supported at this time.
Raises:ValueError – If the digest_size is invalid.
SHA-1

Warning

SHA-1 is a deprecated hash algorithm that has practical known collision attacks. You are strongly discouraged from using it. Existing applications should strongly consider moving away.

class cryptography.hazmat.primitives.hashes.SHA1[source]

SHA-1 is a cryptographic hash function standardized by NIST. It produces an 160-bit message digest. Cryptanalysis of SHA-1 has demonstrated that it is vulnerable to practical collision attacks, and collisions have been demonstrated.

RIPEMD160
class cryptography.hazmat.primitives.hashes.RIPEMD160[source]

RIPEMD160 is a cryptographic hash function that is part of ISO/IEC 10118-3:2004. It produces a 160-bit message digest.

Whirlpool
class cryptography.hazmat.primitives.hashes.Whirlpool[source]

Whirlpool is a cryptographic hash function that is part of ISO/IEC 10118-3:2004. It produces a 512-bit message digest.

MD5

Warning

MD5 is a deprecated hash algorithm that has practical known collision attacks. You are strongly discouraged from using it. Existing applications should strongly consider moving away.

class cryptography.hazmat.primitives.hashes.MD5[source]

MD5 is a deprecated cryptographic hash function. It produces a 128-bit message digest and has practical known collision attacks.

Interfaces
class cryptography.hazmat.primitives.hashes.HashAlgorithm[source]
name
Type:str

The standard name for the hash algorithm, for example: "sha256" or "whirlpool".

digest_size
Type:int

The size of the resulting digest in bytes.

block_size
Type:int

The internal block size of the hash algorithm in bytes.

class cryptography.hazmat.primitives.hashes.HashContext[source]
algorithm

A HashAlgorithm that will be used by this context.

update(data)[source]
Parameters:data (bytes) – The data you want to hash.
finalize()[source]
Returns:The final digest as bytes.
copy()[source]
Returns:A HashContext that is a copy of the current context.

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.

Message authentication codes

While cryptography supports both the CMAC and HMAC algorithms, we strongly recommend that HMAC should be used unless you have a good reason otherwise.

For more information on why HMAC is preferred, see Use cases for CMAC vs. HMAC?

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.

Cipher-based message authentication code

Cipher-based message authentication codes (or CMACs) are a tool for calculating message authentication codes using a block cipher coupled with a secret key. You can use an CMAC to verify both the integrity and authenticity of a message.

A subset of CMAC with the AES-128 algorithm is described in RFC 4493.

class cryptography.hazmat.primitives.cmac.CMAC(algorithm, backend)[source]

New in version 0.4.

CMAC objects take a BlockCipherAlgorithm instance.

>>> from cryptography.hazmat.backends import default_backend
>>> from cryptography.hazmat.primitives import cmac
>>> from cryptography.hazmat.primitives.ciphers import algorithms
>>> c = cmac.CMAC(algorithms.AES(key), backend=default_backend())
>>> c.update(b"message to authenticate")
>>> c.finalize()
'CT\x1d\xc8\x0e\x15\xbe4e\xdb\xb6\x84\xca\xd9Xk'

If the backend doesn’t support the requested algorithm an UnsupportedAlgorithm exception will be raised.

If algorithm isn’t a BlockCipherAlgorithm instance then TypeError will be raised.

To check that a given signature is correct use the verify() method. You will receive an exception if the signature is wrong:

>>> c = cmac.CMAC(algorithms.AES(key), backend=default_backend())
>>> c.update(b"message to authenticate")
>>> c.verify(b"an incorrect signature")
Traceback (most recent call last):
...
cryptography.exceptions.InvalidSignature: Signature did not match digest.
Parameters:
Raises:
update(data)[source]
Parameters:

data (bytes) – The bytes to hash and authenticate.

Raises:
copy()[source]

Copy this CMAC instance, usually so that we may call finalize() to get an intermediate value while we continue to call update() on the original instance.

Returns:A new instance of CMAC that can be updated and finalized independently of the original instance.
Raises:cryptography.exceptions.AlreadyFinalized – See finalize()
verify(signature)[source]

Finalize the current context and securely compare the MAC to signature.

Parameters:

signature (bytes) – The bytes to compare the current CMAC against.

Raises:
finalize()[source]

Finalize the current context and return the message authentication code as bytes.

After finalize has been called this object can no longer be used and update(), copy(), verify() and finalize() will raise an AlreadyFinalized exception.

Return bytes:The message authentication code as bytes.
Raises:cryptography.exceptions.AlreadyFinalized

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.

Hash-based message authentication codes

Hash-based message authentication codes (or HMACs) are a tool for calculating message authentication codes using a cryptographic hash function coupled with a secret key. You can use an HMAC to verify both the integrity and authenticity of a message.

class cryptography.hazmat.primitives.hmac.HMAC(key, algorithm, backend)[source]

HMAC objects take a key and a HashAlgorithm instance. The key should be randomly generated bytes and is recommended to be equal in length to the digest_size of the hash function chosen. You must keep the key secret.

This is an implementation of RFC 2104.

>>> from cryptography.hazmat.backends import default_backend
>>> from cryptography.hazmat.primitives import hashes, hmac
>>> h = hmac.HMAC(key, hashes.SHA256(), backend=default_backend())
>>> h.update(b"message to hash")
>>> h.finalize()
'#F\xdaI\x8b"e\xc4\xf1\xbb\x9a\x8fc\xff\xf5\xdex.\xbc\xcd/+\x8a\x86\x1d\x84\'\xc3\xa6\x1d\xd8J'

If the backend doesn’t support the requested algorithm an UnsupportedAlgorithm exception will be raised.

If algorithm isn’t a HashAlgorithm instance then TypeError will be raised.

To check that a given signature is correct use the verify() method. You will receive an exception if the signature is wrong:

>>> h = hmac.HMAC(key, hashes.SHA256(), backend=default_backend())
>>> h.update(b"message to hash")
>>> h.verify(b"an incorrect signature")
Traceback (most recent call last):
...
cryptography.exceptions.InvalidSignature: Signature did not match digest.
Parameters:
Raises:

cryptography.exceptions.UnsupportedAlgorithm – This is raised if the provided backend does not implement HMACBackend

update(msg)[source]
Parameters:

msg (bytes) – The bytes to hash and authenticate.

Raises:
copy()[source]

Copy this HMAC instance, usually so that we may call finalize() to get an intermediate digest value while we continue to call update() on the original instance.

Returns:A new instance of HMAC that can be updated and finalized independently of the original instance.
Raises:cryptography.exceptions.AlreadyFinalized – See finalize()
verify(signature)[source]

Finalize the current context and securely compare digest to signature.

Parameters:

signature (bytes) – The bytes to compare the current digest against.

Raises:
finalize()[source]

Finalize the current context and return the message digest as bytes.

After finalize has been called this object can no longer be used and update(), copy(), verify() and finalize() will raise an AlreadyFinalized exception.

Return bytes:The message digest as bytes.
Raises:cryptography.exceptions.AlreadyFinalized

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. You may instead be interested in Fernet (symmetric encryption).

Symmetric encryption

Symmetric encryption is a way to encrypt or hide the contents of material where the sender and receiver both use the same secret key. Note that symmetric encryption is not sufficient for most applications because it only provides secrecy but not authenticity. That means an attacker can’t see the message but an attacker can create bogus messages and force the application to decrypt them.

For this reason it is strongly recommended to combine encryption with a message authentication code, such as HMAC, in an “encrypt-then-MAC” formulation as described by Colin Percival.

class cryptography.hazmat.primitives.ciphers.Cipher(algorithm, mode, backend)[source]

Cipher objects combine an algorithm such as AES with a mode like CBC or CTR. A simple example of encrypting and then decrypting content with AES is:

>>> import os
>>> from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
>>> from cryptography.hazmat.backends import default_backend
>>> backend = default_backend()
>>> key = os.urandom(32)
>>> iv = os.urandom(16)
>>> cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
>>> encryptor = cipher.encryptor()
>>> ct = encryptor.update(b"a secret message") + encryptor.finalize()
>>> decryptor = cipher.decryptor()
>>> decryptor.update(ct) + decryptor.finalize()
'a secret message'
Parameters:
Raises:

cryptography.exceptions.UnsupportedAlgorithm – This is raised if the provided backend does not implement CipherBackend

encryptor()[source]
Returns:An encrypting CipherContext instance.

If the backend doesn’t support the requested combination of cipher and mode an UnsupportedAlgorithm exception will be raised.

decryptor()[source]
Returns:A decrypting CipherContext instance.

If the backend doesn’t support the requested combination of cipher and mode an UnsupportedAlgorithm exception will be raised.

Algorithms
class cryptography.hazmat.primitives.ciphers.algorithms.AES(key)[source]

AES (Advanced Encryption Standard) is a block cipher standardized by NIST. AES is both fast, and cryptographically strong. It is a good default choice for encryption.

Parameters:key (bytes) – The secret key. This must be kept secret. Either 128, 192, or 256 bits long.
class cryptography.hazmat.primitives.ciphers.algorithms.Camellia(key)[source]

Camellia is a block cipher approved for use by CRYPTREC and ISO/IEC. It is considered to have comparable security and performance to AES but is not as widely studied or deployed.

Parameters:key (bytes) – The secret key. This must be kept secret. Either 128, 192, or 256 bits long.
class cryptography.hazmat.primitives.ciphers.algorithms.TripleDES(key)[source]

Triple DES (Data Encryption Standard), sometimes referred to as 3DES, is a block cipher standardized by NIST. Triple DES has known crypto-analytic flaws, however none of them currently enable a practical attack. Nonetheless, Triple DES is not recommended for new applications because it is incredibly slow; old applications should consider moving away from it.

Parameters:key (bytes) – The secret key. This must be kept secret. Either 64, 128, or 192 bits long. DES only uses 56, 112, or 168 bits of the key as there is a parity byte in each component of the key. Some writing refers to there being up to three separate keys that are each 56 bits long, they can simply be concatenated to produce the full key.
class cryptography.hazmat.primitives.ciphers.algorithms.CAST5(key)[source]

New in version 0.2.

CAST5 (also known as CAST-128) is a block cipher approved for use in the Canadian government by the Communications Security Establishment. It is a variable key length cipher and supports keys from 40-128 bits in length.

Parameters:key (bytes) – The secret key, This must be kept secret. 40 to 128 bits in length in increments of 8 bits.
class cryptography.hazmat.primitives.ciphers.algorithms.SEED(key)[source]

New in version 0.4.

SEED is a block cipher developed by the Korea Information Security Agency (KISA). It is defined in RFC 4269 and is used broadly throughout South Korean industry, but rarely found elsewhere.

Parameters:key (bytes) – The secret key. This must be kept secret. 128 bits in length.
Weak ciphers

Warning

These ciphers are considered weak for a variety of reasons. New applications should avoid their use and existing applications should strongly consider migrating away.

class cryptography.hazmat.primitives.ciphers.algorithms.Blowfish(key)[source]

Blowfish is a block cipher developed by Bruce Schneier. It is known to be susceptible to attacks when using weak keys. The author has recommended that users of Blowfish move to newer algorithms such as AES.

Parameters:key (bytes) – The secret key. This must be kept secret. 32 to 448 bits in length in increments of 8 bits.
class cryptography.hazmat.primitives.ciphers.algorithms.ARC4(key)[source]

ARC4 (Alleged RC4) is a stream cipher with serious weaknesses in its initial stream output. Its use is strongly discouraged. ARC4 does not use mode constructions.

Parameters:key (bytes) – The secret key. This must be kept secret. Either 40, 56, 64, 80, 128, 192, or 256 bits in length.
>>> from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
>>> from cryptography.hazmat.backends import default_backend
>>> algorithm = algorithms.ARC4(key)
>>> cipher = Cipher(algorithm, mode=None, backend=default_backend())
>>> encryptor = cipher.encryptor()
>>> ct = encryptor.update(b"a secret message")
>>> decryptor = cipher.decryptor()
>>> decryptor.update(ct)
'a secret message'
class cryptography.hazmat.primitives.ciphers.algorithms.IDEA(key)[source]

IDEA (International Data Encryption Algorithm) is a block cipher created in 1991. It is an optional component of the OpenPGP standard. This cipher is susceptible to attacks when using weak keys. It is recommended that you do not use this cipher for new applications.

Parameters:key (bytes) – The secret key. This must be kept secret. 128 bits in length.
Modes
class cryptography.hazmat.primitives.ciphers.modes.CBC(initialization_vector)[source]

CBC (Cipher Block Chaining) is a mode of operation for block ciphers. It is considered cryptographically strong.

Padding is required when using this mode.

Parameters:initialization_vector (bytes) – Must be random bytes. They do not need to be kept secret and they can be included in a transmitted message. Must be the same number of bytes as the block_size of the cipher. Each time something is encrypted a new initialization_vector should be generated. Do not reuse an initialization_vector with a given key, and particularly do not use a constant initialization_vector.

A good construction looks like:

>>> import os
>>> from cryptography.hazmat.primitives.ciphers.modes import CBC
>>> iv = os.urandom(16)
>>> mode = CBC(iv)

While the following is bad and will leak information:

>>> from cryptography.hazmat.primitives.ciphers.modes import CBC
>>> iv = "a" * 16
>>> mode = CBC(iv)
class cryptography.hazmat.primitives.ciphers.modes.CTR(nonce)[source]

Warning

Counter mode is not recommended for use with block ciphers that have a block size of less than 128-bits.

CTR (Counter) is a mode of operation for block ciphers. It is considered cryptographically strong. It transforms a block cipher into a stream cipher.

This mode does not require padding.

Parameters:nonce (bytes) – Should be unique, a nonce. It is critical to never reuse a nonce with a given key. Any reuse of a nonce with the same key compromises the security of every message encrypted with that key. Must be the same number of bytes as the block_size of the cipher with a given key. The nonce does not need to be kept secret and may be included with the ciphertext.
class cryptography.hazmat.primitives.ciphers.modes.OFB(initialization_vector)[source]

OFB (Output Feedback) is a mode of operation for block ciphers. It transforms a block cipher into a stream cipher.

This mode does not require padding.

Parameters:initialization_vector (bytes) – Must be random bytes. They do not need to be kept secret and they can be included in a transmitted message. Must be the same number of bytes as the block_size of the cipher. Do not reuse an initialization_vector with a given key.
class cryptography.hazmat.primitives.ciphers.modes.CFB(initialization_vector)[source]

CFB (Cipher Feedback) is a mode of operation for block ciphers. It transforms a block cipher into a stream cipher.

This mode does not require padding.

Parameters:initialization_vector (bytes) – Must be random bytes. They do not need to be kept secret and they can be included in a transmitted message. Must be the same number of bytes as the block_size of the cipher. Do not reuse an initialization_vector with a given key.
class cryptography.hazmat.primitives.ciphers.modes.CFB8(initialization_vector)[source]

CFB (Cipher Feedback) is a mode of operation for block ciphers. It transforms a block cipher into a stream cipher. The CFB8 variant uses an 8-bit shift register.

This mode does not require padding.

Parameters:initialization_vector (bytes) – Must be random bytes. They do not need to be kept secret and they can be included in a transmitted message. Must be the same number of bytes as the block_size of the cipher. Do not reuse an initialization_vector with a given key.
class cryptography.hazmat.primitives.ciphers.modes.GCM(initialization_vector, tag=None, min_tag_length=16)[source]

Danger

When using this mode you must not use the decrypted data until finalize() has been called. GCM provides no guarantees of ciphertext integrity until decryption is complete.

GCM (Galois Counter Mode) is a mode of operation for block ciphers. An AEAD (authenticated encryption with additional data) mode is a type of block cipher mode that simultaneously encrypts the message as well as authenticating it. Additional unencrypted data may also be authenticated. Additional means of verifying integrity such as HMAC are not necessary.

This mode does not require padding.

Parameters:initialization_vector (bytes) – Must be unique, a nonce. They do not need to be kept secret and they can be included in a transmitted message. NIST recommends a 96-bit IV length for performance critical situations but it can be up to 264 - 1 bits. Do not reuse an initialization_vector with a given key.

Note

Cryptography will generate a 128-bit tag when finalizing encryption. You can shorten a tag by truncating it to the desired length but this is not recommended as it lowers the security margins of the authentication (NIST SP-800-38D recommends 96-bits or greater). Applications wishing to allow truncation must pass the min_tag_length parameter.

Changed in version 0.5: The min_tag_length parameter was added in 0.5, previously truncation down to 4 bytes was always allowed.

Parameters:
  • tag (bytes) – The tag bytes to verify during decryption. When encrypting this must be None.
  • min_tag_length (bytes) – The minimum length tag must be. By default this is 16, meaning tag truncation is not allowed. Allowing tag truncation is strongly discouraged for most applications.
Raises:

ValueError – This is raised if len(tag) < min_tag_length.

An example of securely encrypting and decrypting data with AES in the GCM mode looks like:

import os

from cryptography.hazmat.primitives.ciphers import (
    Cipher, algorithms, modes
)

def encrypt(key, plaintext, associated_data):
    # Generate a random 96-bit IV.
    iv = os.urandom(12)

    # Construct an AES-GCM Cipher object with the given key and a
    # randomly generated IV.
    encryptor = Cipher(
        algorithms.AES(key),
        modes.GCM(iv),
        backend=default_backend()
    ).encryptor()

    # associated_data will be authenticated but not encrypted,
    # it must also be passed in on decryption.
    encryptor.authenticate_additional_data(associated_data)

    # Encrypt the plaintext and get the associated ciphertext.
    # GCM does not require padding.
    ciphertext = encryptor.update(plaintext) + encryptor.finalize()

    return (iv, ciphertext, encryptor.tag)

def decrypt(key, associated_data, iv, ciphertext, tag):
    # Construct a Cipher object, with the key, iv, and additionally the
    # GCM tag used for authenticating the message.
    decryptor = Cipher(
        algorithms.AES(key),
        modes.GCM(iv, tag),
        backend=default_backend()
    ).decryptor()

    # We put associated_data back in or the tag will fail to verify
    # when we finalize the decryptor.
    decryptor.authenticate_additional_data(associated_data)

    # Decryption gets us the authenticated plaintext.
    # If the tag does not match an InvalidTag exception will be raised.
    return decryptor.update(ciphertext) + decryptor.finalize()

iv, ciphertext, tag = encrypt(
    key,
    b"a secret message!",
    b"authenticated but not encrypted payload"
)

print(decrypt(
    key,
    b"authenticated but not encrypted payload",
    iv,
    ciphertext,
    tag
))
a secret message!
Insecure modes

Warning

These modes are insecure. New applications should never make use of them, and existing applications should strongly consider migrating away.

class cryptography.hazmat.primitives.ciphers.modes.ECB[source]

ECB (Electronic Code Book) is the simplest mode of operation for block ciphers. Each block of data is encrypted in the same way. This means identical plaintext blocks will always result in identical ciphertext blocks, which can leave significant patterns in the output.

Padding is required when using this mode.

Interfaces
class cryptography.hazmat.primitives.ciphers.CipherContext[source]

When calling encryptor() or decryptor() on a Cipher object the result will conform to the CipherContext interface. You can then call update(data) with data until you have fed everything into the context. Once that is done call finalize() to finish the operation and obtain the remainder of the data.

Block ciphers require that the plaintext or ciphertext always be a multiple of their block size. Because of that padding is sometimes required to make a message the correct size. CipherContext will not automatically apply any padding; you’ll need to add your own. For block ciphers the recommended padding is PKCS7. If you are using a stream cipher mode (such as CTR) you don’t have to worry about this.

update(data)[source]
Parameters:data (bytes) – The data you wish to pass into the context.
Return bytes:Returns the data that was encrypted or decrypted.
Raises:cryptography.exceptions.AlreadyFinalized – See finalize()

When the Cipher was constructed in a mode that turns it into a stream cipher (e.g. CTR), this will return bytes immediately, however in other modes it will return chunks whose size is determined by the cipher’s block size.

update_into(data, buf)[source]

New in version 1.8.

Warning

This method allows you to avoid a memory copy by passing a writable buffer and reading the resulting data. You are responsible for correctly sizing the buffer and properly handling the data. This method should only be used when extremely high performance is a requirement and you will be making many small calls to update_into.

Parameters:
  • data (bytes) – The data you wish to pass into the context.
  • buf – A writable Python buffer that the data will be written into. This buffer should be len(data) + n - 1 bytes where n is the block size (in bytes) of the cipher and mode combination.
Return int:

Number of bytes written.

Raises:
  • NotImplementedError – This is raised if the version of cffi used is too old (this can happen on older PyPy releases).
  • ValueError – This is raised if the supplied buffer is too small.
>>> import os
>>> from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
>>> from cryptography.hazmat.backends import default_backend
>>> backend = default_backend()
>>> key = os.urandom(32)
>>> iv = os.urandom(16)
>>> cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
>>> encryptor = cipher.encryptor()
>>> # the buffer needs to be at least len(data) + n - 1 where n is cipher/mode block size in bytes
>>> buf = bytearray(31)
>>> len_encrypted = encryptor.update_into(b"a secret message", buf)
>>> # get the ciphertext from the buffer reading only the bytes written to it (len_encrypted)
>>> ct = bytes(buf[:len_encrypted]) + encryptor.finalize()
>>> decryptor = cipher.decryptor()
>>> len_decrypted = decryptor.update_into(ct, buf)
>>> # get the plaintext from the buffer reading only the bytes written (len_decrypted)
>>> bytes(buf[:len_decrypted]) + decryptor.finalize()
'a secret message'
finalize()[source]
Return bytes:Returns the remainder of the data.
Raises:ValueError – This is raised when the data provided isn’t a multiple of the algorithm’s block size.

Once finalize is called this object can no longer be used and update() and finalize() will raise an AlreadyFinalized exception.

class cryptography.hazmat.primitives.ciphers.AEADCipherContext[source]

When calling encryptor or decryptor on a Cipher object with an AEAD mode (e.g. GCM) the result will conform to the AEADCipherContext and CipherContext interfaces. If it is an encryption context it will additionally be an AEADEncryptionContext instance. AEADCipherContext contains an additional method authenticate_additional_data() for adding additional authenticated but unencrypted data (see note below). You should call this before calls to update. When you are done call finalize to finish the operation.

Note

In AEAD modes all data passed to update() will be both encrypted and authenticated. Do not pass encrypted data to the authenticate_additional_data() method. It is meant solely for additional data you may want to authenticate but leave unencrypted.

authenticate_additional_data(data)[source]
Parameters:data (bytes) – Any data you wish to authenticate but not encrypt.
Raises:AlreadyFinalized
class cryptography.hazmat.primitives.ciphers.AEADEncryptionContext[source]

When creating an encryption context using encryptor on a Cipher object with an AEAD mode such as GCM an object conforming to both the AEADEncryptionContext and AEADCipherContext interfaces will be returned. This interface provides one additional attribute tag. tag can only be obtained after finalize has been called.

tag
Return bytes:Returns the tag value as bytes.
Raises:NotYetFinalized if called before the context is finalized.
class cryptography.hazmat.primitives.ciphers.CipherAlgorithm[source]

A named symmetric encryption algorithm.

name
Type:str

The standard name for the mode, for example, “AES”, “Camellia”, or “Blowfish”.

key_size
Type:int

The number of bits in the key being used.

class cryptography.hazmat.primitives.ciphers.BlockCipherAlgorithm[source]

A block cipher algorithm.

block_size
Type:int

The number of bits in a block.

Interfaces used by the symmetric cipher modes described in Symmetric Encryption Modes.

class cryptography.hazmat.primitives.ciphers.modes.Mode[source]

A named cipher mode.

name
Type:str

This should be the standard shorthand name for the mode, for example Cipher-Block Chaining mode is “CBC”.

The name may be used by a backend to influence the operation of a cipher in conjunction with the algorithm’s name.

validate_for_algorithm(algorithm)[source]
Parameters:algorithm (cryptography.hazmat.primitives.ciphers.CipherAlgorithm) –

Checks that the combination of this mode with the provided algorithm meets any necessary invariants. This should raise an exception if they are not met.

For example, the CBC mode uses this method to check that the provided initialization vector’s length matches the block size of the algorithm.

class cryptography.hazmat.primitives.ciphers.modes.ModeWithInitializationVector[source]

A cipher mode with an initialization vector.

initialization_vector
Type:bytes

Exact requirements of the initialization are described by the documentation of individual modes.

class cryptography.hazmat.primitives.ciphers.modes.ModeWithNonce[source]

A cipher mode with a nonce.

nonce
Type:bytes

Exact requirements of the nonce are described by the documentation of individual modes.

class cryptography.hazmat.primitives.ciphers.modes.ModeWithAuthenticationTag[source]

A cipher mode with an authentication tag.

tag
Type:bytes

Exact requirements of the tag are described by the documentation of individual modes.

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.

Padding

Padding is a way to take data that may or may not be a multiple of the block size for a cipher and extend it out so that it is. This is required for many block cipher modes as they require the data to be encrypted to be an exact multiple of the block size.

class cryptography.hazmat.primitives.padding.PKCS7(block_size)[source]

PKCS7 padding is a generalization of PKCS5 padding (also known as standard padding). PKCS7 padding works by appending N bytes with the value of chr(N), where N is the number of bytes required to make the final block of data the same size as the block size. A simple example of padding is:

>>> from cryptography.hazmat.primitives import padding
>>> padder = padding.PKCS7(128).padder()
>>> padded_data = padder.update(b"11111111111111112222222222")
>>> padded_data
'1111111111111111'
>>> padded_data += padder.finalize()
>>> padded_data
'11111111111111112222222222\x06\x06\x06\x06\x06\x06'
>>> unpadder = padding.PKCS7(128).unpadder()
>>> data = unpadder.update(padded_data)
>>> data
'1111111111111111'
>>> data + unpadder.finalize()
'11111111111111112222222222'
Parameters:block_size – The size of the block in bits that the data is being padded to.
Raises:ValueError – Raised if block size is not a multiple of 8 or is not between 0 and 2040 inclusive.
padder()[source]
Returns:A padding PaddingContext instance.
unpadder()[source]
Returns:An unpadding PaddingContext instance.
class cryptography.hazmat.primitives.padding.ANSIX923(block_size)[source]

New in version 1.3.

ANSI X.923 padding works by appending N-1 bytes with the value of 0 and a last byte with the value of chr(N), where N is the number of bytes required to make the final block of data the same size as the block size. A simple example of padding is:

>>> padder = padding.ANSIX923(128).padder()
>>> padded_data = padder.update(b"11111111111111112222222222")
>>> padded_data
'1111111111111111'
>>> padded_data += padder.finalize()
>>> padded_data
'11111111111111112222222222\x00\x00\x00\x00\x00\x06'
>>> unpadder = padding.ANSIX923(128).unpadder()
>>> data = unpadder.update(padded_data)
>>> data
'1111111111111111'
>>> data + unpadder.finalize()
'11111111111111112222222222'
Parameters:block_size – The size of the block in bits that the data is being padded to.
Raises:ValueError – Raised if block size is not a multiple of 8 or is not between 0 and 2040 inclusive.
padder()[source]
Returns:A padding PaddingContext instance.
unpadder()[source]
Returns:An unpadding PaddingContext instance.
class cryptography.hazmat.primitives.padding.PaddingContext[source]

When calling padder() or unpadder() the result will conform to the PaddingContext interface. You can then call update(data) with data until you have fed everything into the context. Once that is done call finalize() to finish the operation and obtain the remainder of the data.

update(data)[source]
Parameters:

data (bytes) – The data you wish to pass into the context.

Return bytes:

Returns the data that was padded or unpadded.

Raises:
finalize()[source]

Finalize the current context and return the rest of the data.

After finalize has been called this object can no longer be used; update() and finalize() will raise an AlreadyFinalized exception.

Return bytes:

Returns the remainder of the data.

Raises:
  • TypeError – Raised if data is not bytes.
  • ValueError – When trying to remove padding from incorrectly padded data.

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.

Key derivation functions

Key derivation functions derive bytes suitable for cryptographic operations from passwords or other data sources using a pseudo-random function (PRF). Different KDFs are suitable for different tasks such as:

  • Cryptographic key derivation

    Deriving a key suitable for use as input to an encryption algorithm. Typically this means taking a password and running it through an algorithm such as PBKDF2HMAC or HKDF. This process is typically known as key stretching.

  • Password storage

    When storing passwords you want to use an algorithm that is computationally intensive. Legitimate users will only need to compute it once (for example, taking the user’s password, running it through the KDF, then comparing it to the stored value), while attackers will need to do it billions of times. Ideal password storage KDFs will be demanding on both computational and memory resources.

class cryptography.hazmat.primitives.kdf.pbkdf2.PBKDF2HMAC(algorithm, length, salt, iterations, backend)[source]

New in version 0.2.

PBKDF2 (Password Based Key Derivation Function 2) is typically used for deriving a cryptographic key from a password. It may also be used for key storage, but an alternate key storage KDF such as Scrypt is generally considered a better solution.

This class conforms to the KeyDerivationFunction interface.

>>> import os
>>> from cryptography.hazmat.primitives import hashes
>>> from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
>>> from cryptography.hazmat.backends import default_backend
>>> backend = default_backend()
>>> salt = os.urandom(16)
>>> # derive
>>> kdf = PBKDF2HMAC(
...     algorithm=hashes.SHA256(),
...     length=32,
...     salt=salt,
...     iterations=100000,
...     backend=backend
... )
>>> key = kdf.derive(b"my great password")
>>> # verify
>>> kdf = PBKDF2HMAC(
...     algorithm=hashes.SHA256(),
...     length=32,
...     salt=salt,
...     iterations=100000,
...     backend=backend
... )
>>> kdf.verify(b"my great password", key)
Parameters:
  • algorithm – An instance of HashAlgorithm.
  • length (int) – The desired length of the derived key. Maximum is (232 - 1) * algorithm.digest_size.
  • salt (bytes) – A salt. NIST SP 800-132 recommends 128-bits or longer.
  • iterations (int) – The number of iterations to perform of the hash function. This can be used to control the length of time the operation takes. Higher numbers help mitigate brute force attacks against derived keys. See OWASP’s Password Storage Cheat Sheet for more detailed recommendations if you intend to use this for password storage.
  • backend – An instance of PBKDF2HMACBackend.
Raises:
derive(key_material)[source]
Parameters:

key_material (bytes) – The input key material. For PBKDF2 this should be a password.

Return bytes:

the derived key.

Raises:

This generates and returns a new key from the supplied password.

verify(key_material, expected_key)[source]
Parameters:
  • key_material (bytes) – The input key material. This is the same as key_material in derive().
  • expected_key (bytes) – The expected result of deriving a new key, this is the same as the return value of derive().
Raises:

This checks whether deriving a new key from the supplied key_material generates the same key as the expected_key, and raises an exception if they do not match. This can be used for checking whether the password a user provides matches the stored derived key.

class cryptography.hazmat.primitives.kdf.hkdf.HKDF(algorithm, length, salt, info, backend)[source]

New in version 0.2.

HKDF (HMAC-based Extract-and-Expand Key Derivation Function) is suitable for deriving keys of a fixed size used for other cryptographic operations.

Warning

HKDF should not be used for password storage.

>>> import os
>>> from cryptography.hazmat.primitives import hashes
>>> from cryptography.hazmat.primitives.kdf.hkdf import HKDF
>>> from cryptography.hazmat.backends import default_backend
>>> backend = default_backend()
>>> salt = os.urandom(16)
>>> info = b"hkdf-example"
>>> hkdf = HKDF(
...     algorithm=hashes.SHA256(),
...     length=32,
...     salt=salt,
...     info=info,
...     backend=backend
... )
>>> key = hkdf.derive(b"input key")
>>> hkdf = HKDF(
...     algorithm=hashes.SHA256(),
...     length=32,
...     salt=salt,
...     info=info,
...     backend=backend
... )
>>> hkdf.verify(b"input key", key)
Parameters:
  • algorithm – An instance of HashAlgorithm.
  • length (int) – The desired length of the derived key. Maximum is 255 * (algorithm.digest_size // 8).
  • salt (bytes) – A salt. Randomizes the KDF’s output. Optional, but highly recommended. Ideally as many bits of entropy as the security level of the hash: often that means cryptographically random and as long as the hash output. Worse (shorter, less entropy) salt values can still meaningfully contribute to security. May be reused. Does not have to be secret, but may cause stronger security guarantees if secret; see RFC 5869 and the HKDF paper for more details. If None is explicitly passed a default salt of algorithm.digest_size // 8 null bytes will be used.
  • info (bytes) – Application specific context information. If None is explicitly passed an empty byte string will be used.
  • backend – An instance of HMACBackend.
Raises:
derive(key_material)[source]
Parameters:key_material (bytes) – The input key material.
Return bytes:The derived key.
Raises:TypeError – This exception is raised if key_material is not bytes.

Derives a new key from the input key material by performing both the extract and expand operations.

verify(key_material, expected_key)[source]
Parameters:
  • key_material (bytes) – The input key material. This is the same as key_material in derive().
  • expected_key (bytes) – The expected result of deriving a new key, this is the same as the return value of derive().
Raises:

This checks whether deriving a new key from the supplied key_material generates the same key as the expected_key, and raises an exception if they do not match.

class cryptography.hazmat.primitives.kdf.hkdf.HKDFExpand(algorithm, length, info, backend)[source]

New in version 0.5.

HKDF consists of two stages, extract and expand. This class exposes an expand only version of HKDF that is suitable when the key material is already cryptographically strong.

Warning

HKDFExpand should only be used if the key material is cryptographically strong. You should use HKDF if you are unsure.

>>> import os
>>> from cryptography.hazmat.primitives import hashes
>>> from cryptography.hazmat.primitives.kdf.hkdf import HKDFExpand
>>> from cryptography.hazmat.backends import default_backend
>>> backend = default_backend()
>>> info = b"hkdf-example"
>>> key_material = os.urandom(16)
>>> hkdf = HKDFExpand(
...     algorithm=hashes.SHA256(),
...     length=32,
...     info=info,
...     backend=backend
... )
>>> key = hkdf.derive(key_material)
>>> hkdf = HKDFExpand(
...     algorithm=hashes.SHA256(),
...     length=32,
...     info=info,
...     backend=backend
... )
>>> hkdf.verify(key_material, key)
Parameters:
  • algorithm – An instance of HashAlgorithm.
  • length (int) – The desired length of the derived key. Maximum is 255 * (algorithm.digest_size // 8).
  • info (bytes) – Application specific context information. If None is explicitly passed an empty byte string will be used.
  • backend – An instance of HMACBackend.
Raises:
derive(key_material)[source]
Parameters:

key_material (bytes) – The input key material.

Return bytes:

The derived key.

Raises:
  • TypeError – This is raised if the provided key_material is a unicode object
  • TypeError – This exception is raised if key_material is not bytes.

Derives a new key from the input key material by performing both the extract and expand operations.

verify(key_material, expected_key)[source]
Parameters:
  • key_material (bytes) – The input key material. This is the same as key_material in derive().
  • expected_key (bytes) – The expected result of deriving a new key, this is the same as the return value of derive().
Raises:

This checks whether deriving a new key from the supplied key_material generates the same key as the expected_key, and raises an exception if they do not match.

class cryptography.hazmat.primitives.kdf.concatkdf.ConcatKDFHash(algorithm, length, otherinfo, backend)[source]

New in version 1.0.

ConcatKDFHash (Concatenation Key Derivation Function) is defined by the NIST Special Publication NIST SP 800-56Ar2 document, to be used to derive keys for use after a Key Exchange negotiation operation.

Warning

ConcatKDFHash should not be used for password storage.

>>> import os
>>> from cryptography.hazmat.primitives import hashes
>>> from cryptography.hazmat.primitives.kdf.concatkdf import ConcatKDFHash
>>> from cryptography.hazmat.backends import default_backend
>>> backend = default_backend()
>>> otherinfo = b"concatkdf-example"
>>> ckdf = ConcatKDFHash(
...     algorithm=hashes.SHA256(),
...     length=256,
...     otherinfo=otherinfo,
...     backend=backend
... )
>>> key = ckdf.derive(b"input key")
>>> ckdf = ConcatKDFHash(
...     algorithm=hashes.SHA256(),
...     length=256,
...     otherinfo=otherinfo,
...     backend=backend
... )
>>> ckdf.verify(b"input key", key)
Parameters:
  • algorithm – An instance of HashAlgorithm.
  • length (int) – The desired length of the derived key in bytes. Maximum is hashlen * (2^32 -1).
  • otherinfo (bytes) – Application specific context information. If None is explicitly passed an empty byte string will be used.
  • backend – An instance of HashBackend.
Raises:
derive(key_material)[source]
Parameters:key_material (bytes) – The input key material.
Return bytes:The derived key.
Raises:TypeError – This exception is raised if key_material is not bytes.

Derives a new key from the input key material.

verify(key_material, expected_key)[source]
Parameters:
  • key_material (bytes) – The input key material. This is the same as key_material in derive().
  • expected_key (bytes) – The expected result of deriving a new key, this is the same as the return value of derive().
Raises:

This checks whether deriving a new key from the supplied key_material generates the same key as the expected_key, and raises an exception if they do not match.

class cryptography.hazmat.primitives.kdf.concatkdf.ConcatKDFHMAC(algorithm, length, salt, otherinfo, backend)[source]

New in version 1.0.

Similar to ConcatKFDHash but uses an HMAC function instead.

Warning

ConcatKDFHMAC should not be used for password storage.

>>> import os
>>> from cryptography.hazmat.primitives import hashes
>>> from cryptography.hazmat.primitives.kdf.concatkdf import ConcatKDFHMAC
>>> from cryptography.hazmat.backends import default_backend
>>> backend = default_backend()
>>> salt = os.urandom(16)
>>> otherinfo = b"concatkdf-example"
>>> ckdf = ConcatKDFHMAC(
...     algorithm=hashes.SHA256(),
...     length=256,
...     salt=salt,
...     otherinfo=otherinfo,
...     backend=backend
... )
>>> key = ckdf.derive(b"input key")
>>> ckdf = ConcatKDFHMAC(
...     algorithm=hashes.SHA256(),
...     length=256,
...     salt=salt,
...     otherinfo=otherinfo,
...     backend=backend
... )
>>> ckdf.verify(b"input key", key)
Parameters:
  • algorithm – An instance of HashAlgorithm.
  • length (int) – The desired length of the derived key in bytes. Maximum is hashlen * (2^32 -1).
  • salt (bytes) – A salt. Randomizes the KDF’s output. Optional, but highly recommended. Ideally as many bits of entropy as the security level of the hash: often that means cryptographically random and as long as the hash output. Does not have to be secret, but may cause stronger security guarantees if secret; If None is explicitly passed a default salt of algorithm.block_size null bytes will be used.
  • otherinfo (bytes) – Application specific context information. If None is explicitly passed an empty byte string will be used.
  • backend – An instance of HMACBackend.
Raises:
derive(key_material)[source]
Parameters:key_material (bytes) – The input key material.
Return bytes:The derived key.
Raises:TypeError – This exception is raised if key_material is not bytes.

Derives a new key from the input key material.

verify(key_material, expected_key)[source]
Parameters:
  • key_material (bytes) – The input key material. This is the same as key_material in derive().
  • expected_key (bytes) – The expected result of deriving a new key, this is the same as the return value of derive().
Raises:

This checks whether deriving a new key from the supplied key_material generates the same key as the expected_key, and raises an exception if they do not match.

class cryptography.hazmat.primitives.kdf.x963kdf.X963KDF(algorithm, length, otherinfo, backend)[source]

New in version 1.1.

X963KDF (ANSI X9.63 Key Derivation Function) is defined by ANSI in the ANSI X9.63:2001 document, to be used to derive keys for use after a Key Exchange negotiation operation.

SECG in SEC 1 v2.0 recommends that ConcatKDFHash be used for new projects. This KDF should only be used for backwards compatibility with pre-existing protocols.

Warning

X963KDF should not be used for password storage.

>>> import os
>>> from cryptography.hazmat.primitives import hashes
>>> from cryptography.hazmat.primitives.kdf.x963kdf import X963KDF
>>> from cryptography.hazmat.backends import default_backend
>>> backend = default_backend()
>>> sharedinfo = b"ANSI X9.63 Example"
>>> xkdf = X963KDF(
...     algorithm=hashes.SHA256(),
...     length=256,
...     sharedinfo=sharedinfo,
...     backend=backend
... )
>>> key = xkdf.derive(b"input key")
>>> xkdf = X963KDF(
...     algorithm=hashes.SHA256(),
...     length=256,
...     sharedinfo=sharedinfo,
...     backend=backend
... )
>>> xkdf.verify(b"input key", key)
Parameters:
  • algorithm – An instance of HashAlgorithm.
  • length (int) – The desired length of the derived key in bytes. Maximum is hashlen * (2^32 -1).
  • sharedinfo (bytes) – Application specific context information. If None is explicitly passed an empty byte string will be used.
  • backend – A cryptography backend HashBackend instance.
Raises:
derive(key_material)[source]
Parameters:key_material (bytes) – The input key material.
Return bytes:The derived key.
Raises:TypeError – This exception is raised if key_material is not bytes.

Derives a new key from the input key material.

verify(key_material, expected_key)[source]
Parameters:
  • key_material (bytes) – The input key material. This is the same as key_material in derive().
  • expected_key (bytes) – The expected result of deriving a new key, this is the same as the return value of derive().
Raises:

This checks whether deriving a new key from the supplied key_material generates the same key as the expected_key, and raises an exception if they do not match.

class cryptography.hazmat.primitives.kdf.kbkdf.KBKDFHMAC(algorithm, mode, length, rlen, llen, location, label, context, fixed, backend)[source]

New in version 1.4.

KBKDF (Key Based Key Derivation Function) is defined by the NIST SP 800-108 document, to be used to derive additional keys from a key that has been established through an automated key-establishment scheme.

Warning

KBKDFHMAC should not be used for password storage.

>>> import os
>>> from cryptography.hazmat.primitives import hashes
>>> from cryptography.hazmat.primitives.kdf.kbkdf import (
...    CounterLocation, KBKDFHMAC, Mode
... )
>>> from cryptography.hazmat.backends import default_backend
>>> backend = default_backend()
>>> label = b"KBKDF HMAC Label"
>>> context = b"KBKDF HMAC Context"
>>> kdf = KBKDFHMAC(
...     algorithm=hashes.SHA256(),
...     mode=Mode.CounterMode,
...     length=256,
...     rlen=4,
...     llen=4,
...     location=CounterLocation.BeforeFixed,
...     label=label,
...     context=context,
...     fixed=None,
...     backend=backend
... )
>>> key = kdf.derive(b"input key")
>>> kdf = KBKDFHMAC(
...     algorithm=hashes.SHA256(),
...     mode=Mode.CounterMode,
...     length=256,
...     rlen=4,
...     llen=4,
...     location=CounterLocation.BeforeFixed,
...     label=label,
...     context=context,
...     fixed=None,
...     backend=backend
... )
>>> kdf.verify(b"input key", key)
Parameters:
  • algorithm – An instance of HashAlgorithm.
  • mode – The desired mode of the PRF. A value from the Mode enum.
  • length (int) – The desired length of the derived key in bytes.
  • rlen (int) – An integer that indicates the length of the binary representation of the counter in bytes.
  • llen (int) – An integer that indicates the binary representation of the length in bytes.
  • location – The desired location of the counter. A value from the CounterLocation enum.
  • label (bytes) – Application specific label information. If None is explicitly passed an empty byte string will be used.
  • context (bytes) – Application specific context information. If None is explicitly passed an empty byte string will be used.
  • fixed (bytes) – Instead of specifying label and context you may supply your own fixed data. If fixed is specified, label and context is ignored.
  • backend – A cryptography backend HashBackend instance.
Raises:
  • cryptography.exceptions.UnsupportedAlgorithm – This is raised if the provided backend does not implement HashBackend
  • TypeError – This exception is raised if label or context is not bytes. Also raised if rlen or llen is not int.
  • ValueError – This exception is raised if rlen or llen is greater than 4 or less than 1. This exception is also raised if you specify a label or context and fixed.
derive(key_material)[source]
Parameters:key_material (bytes) – The input key material.
Return bytes:The derived key.
Raises:TypeError – This exception is raised if key_material is not bytes.

Derives a new key from the input key material.

verify(key_material, expected_key)[source]
Parameters:
  • key_material (bytes) – The input key material. This is the same as key_material in derive().
  • expected_key (bytes) – The expected result of deriving a new key, this is the same as the return value of derive().
Raises:

This checks whether deriving a new key from the supplied key_material generates the same key as the expected_key, and raises an exception if they do not match.

class cryptography.hazmat.primitives.kdf.kbkdf.Mode[source]

An enumeration for the key based key derivative modes.

CounterMode

The output of the PRF is computed with a counter as the iteration variable.

class cryptography.hazmat.primitives.kdf.kbkdf.CounterLocation[source]

An enumeration for the key based key derivative counter location.

BeforeFixed

The counter iteration variable will be concatenated before the fixed input data.

AfterFixed

The counter iteration variable will be concatenated after the fixed input data.

class cryptography.hazmat.primitives.kdf.scrypt.Scrypt(salt, length, n, r, p, backend)[source]

New in version 1.6.

Scrypt is a KDF designed for password storage by Colin Percival to be resistant against hardware-assisted attackers by having a tunable memory cost. It is described in RFC 7914.

This class conforms to the KeyDerivationFunction interface.

>>> import os
>>> from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
>>> from cryptography.hazmat.backends import default_backend
>>> backend = default_backend()
>>> salt = os.urandom(16)
>>> # derive
>>> kdf = Scrypt(
...     salt=salt,
...     length=64,
...     n=2**14,
...     r=8,
...     p=1,
...     backend=backend
... )
>>> key = kdf.derive(b"my great password")
>>> # verify
>>> kdf = Scrypt(
...     salt=salt,
...     length=64,
...     n=2**14,
...     r=8,
...     p=1,
...     backend=backend
... )
>>> kdf.verify(b"my great password", key)
Parameters:
  • salt (bytes) – A salt.
  • length (int) – The desired length of the derived key.
  • n (int) – CPU/Memory cost parameter. It must be larger than 1 and be a power of 2.
  • r (int) – Block size parameter.
  • p (int) – Parallelization parameter.

The computational and memory cost of Scrypt can be adjusted by manipulating the 3 parameters: n, r, and p. In general, the memory cost of Scrypt is affected by the values of both n and r, while n also determines the number of iterations performed. p increases the computational cost without affecting memory usage. A more in-depth explanation of the 3 parameters can be found here.

RFC 7914 recommends values of r=8 and p=1 while scaling n to a number appropriate for your system. The scrypt paper suggests a minimum value of n=2**14 for interactive logins (t < 100ms), or n=2**20 for more sensitive files (t < 5s).

Parameters:

backend – An instance of ScryptBackend.

Raises:
derive(key_material)[source]
Parameters:

key_material (bytes) – The input key material.

Return bytes:

the derived key.

Raises:

This generates and returns a new key from the supplied password.

verify(key_material, expected_key)[source]
Parameters:
  • key_material (bytes) – The input key material. This is the same as key_material in derive().
  • expected_key (bytes) – The expected result of deriving a new key, this is the same as the return value of derive().
Raises:

This checks whether deriving a new key from the supplied key_material generates the same key as the expected_key, and raises an exception if they do not match. This can be used for checking whether the password a user provides matches the stored derived key.

Interface
class cryptography.hazmat.primitives.kdf.KeyDerivationFunction[source]

New in version 0.2.

derive(key_material)[source]
Parameters:key_material (bytes) – The input key material. Depending on what key derivation function you are using this could be either random bytes, or a user supplied password.
Returns:The new key.
Raises:cryptography.exceptions.AlreadyFinalized – This is raised when derive() or verify() is called more than once.

This generates and returns a new key from the supplied key material.

verify(key_material, expected_key)[source]
Parameters:
  • key_material (bytes) – The input key material. This is the same as key_material in derive().
  • expected_key (bytes) – The expected result of deriving a new key, this is the same as the return value of derive().
Raises:

This checks whether deriving a new key from the supplied key_material generates the same key as the expected_key, and raises an exception if they do not match. This can be used for something like checking whether a user’s password attempt matches the stored derived key.

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.

Key wrapping

Key wrapping is a cryptographic construct that uses symmetric encryption to encapsulate key material. Key wrapping algorithms are occasionally utilized to protect keys at rest or transmit them over insecure networks. Many of the protections offered by key wrapping are also offered by using authenticated symmetric encryption.

cryptography.hazmat.primitives.keywrap.aes_key_wrap(wrapping_key, key_to_wrap, backend)[source]

New in version 1.1.

This function performs AES key wrap (without padding) as specified in RFC 3394.

Parameters:
  • wrapping_key (bytes) – The wrapping key.
  • key_to_wrap (bytes) – The key to wrap.
  • backend – A CipherBackend instance that supports AES.
Return bytes:

The wrapped key as bytes.

cryptography.hazmat.primitives.keywrap.aes_key_unwrap(wrapping_key, wrapped_key, backend)[source]

New in version 1.1.

This function performs AES key unwrap (without padding) as specified in RFC 3394.

Parameters:
  • wrapping_key (bytes) – The wrapping key.
  • wrapped_key (bytes) – The wrapped key.
  • backend – A CipherBackend instance that supports AES.
Return bytes:

The unwrapped key as bytes.

Raises:

cryptography.hazmat.primitives.keywrap.InvalidUnwrap – This is raised if the key is not successfully unwrapped.

Exceptions
class cryptography.hazmat.primitives.keywrap.InvalidUnwrap[source]

This is raised when a wrapped key fails to unwrap. It can be caused by a corrupted or invalid wrapped key or an invalid wrapping key.

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.

Asymmetric algorithms

Asymmetric cryptography is a branch of cryptography where a secret key can be divided into two parts, a public key and a private key. The public key can be given to anyone, trusted or not, while the private key must be kept secret (just like the key in symmetric cryptography).

Asymmetric cryptography has two primary use cases: authentication and confidentiality. Using asymmetric cryptography, messages can be signed with a private key, and then anyone with the public key is able to verify that the message was created by someone possessing the corresponding private key. This can be combined with a proof of identity system to know what entity (person or group) actually owns that private key, providing authentication.

Encryption with asymmetric cryptography works in a slightly different way from symmetric encryption. Someone with the public key is able to encrypt a message, providing confidentiality, and then only the person in possession of the private key is able to decrypt it.

Cryptography supports three different sets of asymmetric algorithms: RSA, DSA, and Elliptic Curve.

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.

DSA

DSA is a public-key algorithm for signing messages.

Generation
cryptography.hazmat.primitives.asymmetric.dsa.generate_private_key(key_size, backend)[source]

New in version 0.5.

Generate a DSA private key from the given key size. This function will generate a new set of parameters and key in one step.

Parameters:
  • key_size (int) – The length of the modulus in bits. It should be either 1024, 2048 or 3072. For keys generated in 2015 this should be at least 2048 (See page 41). Note that some applications (such as SSH) have not yet gained support for larger key sizes specified in FIPS 186-3 and are still restricted to only the 1024-bit keys specified in FIPS 186-2.
  • backend – An instance of DSABackend.
Returns:

An instance of DSAPrivateKey.

Raises:

cryptography.exceptions.UnsupportedAlgorithm – This is raised if the provided backend does not implement DSABackend

cryptography.hazmat.primitives.asymmetric.dsa.generate_parameters(key_size, backend)[source]

New in version 0.5.

Generate DSA parameters using the provided backend.

Parameters:
  • key_size (int) – The length of q. It should be either 1024, 2048 or 3072. For keys generated in 2015 this should be at least 2048 (See page 41). Note that some applications (such as SSH) have not yet gained support for larger key sizes specified in FIPS 186-3 and are still restricted to only the 1024-bit keys specified in FIPS 186-2.
  • backend – An instance of DSABackend.
Returns:

An instance of DSAParameters.

Raises:

cryptography.exceptions.UnsupportedAlgorithm – This is raised if the provided backend does not implement DSABackend

Signing

Using a DSAPrivateKey instance.

>>> from cryptography.hazmat.backends import default_backend
>>> from cryptography.hazmat.primitives import hashes
>>> from cryptography.hazmat.primitives.asymmetric import dsa
>>> private_key = dsa.generate_private_key(
...     key_size=1024,
...     backend=default_backend()
... )
>>> signer = private_key.signer(hashes.SHA256())
>>> data = b"this is some data I'd like to sign"
>>> signer.update(data)
>>> signature = signer.finalize()

There is a shortcut to sign sufficiently short messages directly:

>>> data = b"this is some data I'd like to sign"
>>> signature = private_key.sign(
...     data,
...     hashes.SHA256()
... )

The signature is a bytes object, whose contents is DER encoded as described in RFC 3279. This can be decoded using decode_dss_signature().

Verification

Verification is performed using a DSAPublicKey instance. You can get a public key object with load_pem_public_key(), load_der_public_key(), public_key() , or public_key().

>>> public_key = private_key.public_key()
>>> verifier = public_key.verifier(signature, hashes.SHA256())
>>> verifier.update(data)
>>> verifier.verify()

There is a shortcut to verify sufficiently short messages directly:

>>> public_key.verify(
...     signature,
...     data,
...     hashes.SHA256()
... )

verifier() takes the signature in the same format as is returned by signer.finalize().

verify() will raise an InvalidSignature exception if the signature isn’t valid.

Numbers
class cryptography.hazmat.primitives.asymmetric.dsa.DSAParameterNumbers(p, q, g)[source]

New in version 0.5.

The collection of integers that make up a set of DSA parameters.

p
Type:int

The public modulus.

q
Type:int

The sub-group order.

g
Type:int

The generator.

parameters(backend)[source]
Parameters:backend – An instance of DSABackend.
Returns:A new instance of DSAParameters.
class cryptography.hazmat.primitives.asymmetric.dsa.DSAPublicNumbers(y, parameter_numbers)[source]

New in version 0.5.

The collection of integers that make up a DSA public key.

y
Type:int

The public value y.

parameter_numbers
Type:DSAParameterNumbers

The DSAParameterNumbers associated with the public key.

public_key(backend)[source]
Parameters:backend – An instance of DSABackend.
Returns:A new instance of DSAPublicKey.
class cryptography.hazmat.primitives.asymmetric.dsa.DSAPrivateNumbers(x, public_numbers)[source]

New in version 0.5.

The collection of integers that make up a DSA private key.

Warning

Revealing the value of x will compromise the security of any cryptographic operations performed.

x
Type:int

The private value x.

public_numbers
Type:DSAPublicNumbers

The DSAPublicNumbers associated with the private key.

private_key(backend)[source]
Parameters:backend – An instance of DSABackend.
Returns:A new instance of DSAPrivateKey.
Key interfaces
class cryptography.hazmat.primitives.asymmetric.dsa.DSAParameters[source]

New in version 0.3.

DSA parameters.

generate_private_key()[source]

New in version 0.5.

Generate a DSA private key. This method can be used to generate many new private keys from a single set of parameters.

Returns:An instance of DSAPrivateKey.
class cryptography.hazmat.primitives.asymmetric.dsa.DSAParametersWithNumbers[source]

New in version 0.5.

Extends DSAParameters.

parameter_numbers()[source]

Create a DSAParameterNumbers object.

Returns:A DSAParameterNumbers instance.
class cryptography.hazmat.primitives.asymmetric.dsa.DSAPrivateKey[source]

New in version 0.3.

A DSA private key.

public_key()[source]
Returns:DSAPublicKey

An DSA public key object corresponding to the values of the private key.

parameters()[source]
Returns:DSAParameters

The DSAParameters object associated with this private key.

signer(algorithm, backend)[source]

New in version 0.4.

Sign data which can be verified later by others using the public key. The signature is formatted as DER-encoded bytes, as specified in RFC 3279.

Parameters:
Returns:

AsymmetricSignatureContext

key_size
Type:int

The bit length of q.

sign(data, algorithm)[source]

New in version 1.5.

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

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

Parameters:
  • data (bytes) – The message string to sign.
  • algorithm – An instance of HashAlgorithm or Prehashed if the data you want to sign has already been hashed.
Return bytes:

Signature.

class cryptography.hazmat.primitives.asymmetric.dsa.DSAPrivateKeyWithSerialization[source]

New in version 0.8.

Extends DSAPrivateKey.

private_numbers()[source]

Create a DSAPrivateNumbers object.

Returns:A DSAPrivateNumbers instance.
private_bytes(encoding, format, encryption_algorithm)[source]

Allows serialization of the key to bytes. Encoding ( PEM or DER), format ( TraditionalOpenSSL 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.dsa.DSAPublicKey[source]

New in version 0.3.

A DSA public key.

key_size
Type:int

The bit length of q.

parameters()[source]
Returns:DSAParameters

The DSAParameters object associated with this public key.

verifier(signature, algorithm, backend)[source]

New in version 0.4.

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

Parameters:
Returns:

AsymmetricVerificationContext

public_numbers()[source]

Create a DSAPublicNumbers object.

Returns:A DSAPublicNumbers instance.
public_bytes(encoding, format)[source]

Allows serialization of the key to bytes. Encoding ( PEM or DER) and format ( SubjectPublicKeyInfo) are chosen to define the exact serialization.

Parameters:
Return bytes:

Serialized key.

verify(signature, data, algorithm)[source]

New in version 1.5.

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

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

Parameters:
  • signature (bytes) – The signature to verify.
  • data (bytes) – The message string that was signed.
  • algorithm – An instance of HashAlgorithm or Prehashed if the data you want to sign has already been hashed.
Raises:

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

class cryptography.hazmat.primitives.asymmetric.dsa.DSAPublicKeyWithSerialization

New in version 0.8.

Alias for DSAPublicKey.

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, backend)[source]

New in version 0.5.

Generate a new private key on curve for use with backend.

Parameters:
Returns:

A new instance of EllipticCurvePrivateKey.

cryptography.hazmat.primitives.asymmetric.ec.derive_private_key(private_value, curve, backend)[source]

New in version 1.6.

Derive a private key from private_value on curve for use with backend.

Parameters:
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.

Parameters:algorithm – An instance of 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()
... )
>>> signer = private_key.signer(ec.ECDSA(hashes.SHA256()))
>>> signer.update(b"this is some data I'd like")
>>> signer.update(b" to sign")
>>> signature = signer.finalize()

There is a shortcut to sign sufficiently short messages directly:

>>> 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 RFC 3279. This can be decoded using decode_dss_signature().

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()
>>> verifier = public_key.verifier(signature, ec.ECDSA(hashes.SHA256()))
>>> verifier.update(b"this is some data I'd like")
>>> verifier.update(b" to sign")
>>> verifier.verify()
True

The last call will either return True or raise an InvalidSignature exception.

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
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(backend)[source]

Convert a collection of numbers into a private key suitable for doing actual cryptographic operations.

Parameters:backend – An instance of EllipticCurveBackend.
Returns:A new instance of EllipticCurvePrivateKey.
class cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicNumbers(x, y, curve)[source]

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(backend)[source]

Convert a collection of numbers into a public key suitable for doing actual cryptographic operations.

Parameters:backend – An instance of EllipticCurveBackend.
Returns:A new instance of EllipticCurvePublicKey.
encode_point()[source]

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)[source]

New in version 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.

Parameters:
Returns:

An EllipticCurvePublicNumbers instance.

Raises:
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 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.

>>> from cryptography.hazmat.backends import default_backend
>>> from cryptography.hazmat.primitives.asymmetric import ec
>>> private_key = ec.generate_private_key(
...     ec.SECP384R1(), default_backend()
... )
>>> peer_public_key = ec.generate_private_key(
...     ec.SECP384R1(), default_backend()
... ).public_key()
>>> shared_key = private_key.exchange(ec.ECDH(), peer_public_key)

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.

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.SECT571K1[source]

New in version 0.5.

SECG curve sect571k1. Also called NIST K-571.

class cryptography.hazmat.primitives.asymmetric.ec.SECT409K1[source]

New in version 0.5.

SECG curve sect409k1. Also called NIST K-409.

class cryptography.hazmat.primitives.asymmetric.ec.SECT283K1[source]

New in version 0.5.

SECG curve sect283k1. Also called NIST K-283.

class cryptography.hazmat.primitives.asymmetric.ec.SECT233K1[source]

New in version 0.5.

SECG curve sect233k1. Also called NIST K-233.

class cryptography.hazmat.primitives.asymmetric.ec.SECT163K1[source]

New in version 0.5.

SECG curve sect163k1. Also called NIST K-163.

class cryptography.hazmat.primitives.asymmetric.ec.SECT571R1[source]

New in version 0.5.

SECG curve sect571r1. Also called NIST B-571.

class cryptography.hazmat.primitives.asymmetric.ec.SECT409R1[source]

New in version 0.5.

SECG curve sect409r1. Also called NIST B-409.

class cryptography.hazmat.primitives.asymmetric.ec.SECT283R1[source]

New in version 0.5.

SECG curve sect283r1. Also called NIST B-283.

class cryptography.hazmat.primitives.asymmetric.ec.SECT233R1[source]

New in version 0.5.

SECG curve sect233r1. Also called NIST B-233.

class cryptography.hazmat.primitives.asymmetric.ec.SECT163R2[source]

New in version 0.5.

SECG curve sect163r2. Also called NIST B-163.

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.SECP384R1[source]

New in version 0.5.

SECG curve secp384r1. Also called NIST P-384.

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.SECT224R1

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.

Key Interfaces
class cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve[source]

New in version 0.5.

A named elliptic curve.

name
Type:string

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[source]

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[source]

New in version 0.5.

An elliptic curve private key for use with an algorithm such as ECDSA or EdDSA.

signer(signature_algorithm)[source]

Sign data which can be verified later by others using the public key. The signature is formatted as DER-encoded bytes, as specified in RFC 3279.

Parameters:signature_algorithm – An instance of EllipticCurveSignatureAlgorithm.
Returns:AsymmetricSignatureContext
exchange(algorithm, peer_public_key)[source]

New in version 1.1.

Perform’s a key exchange operation using the provided algorithm with the peer’s public key.

For most applications the result should be passed to a key derivation function.

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()[source]
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:

Signature.

class cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKeyWithSerialization[source]

New in version 0.8.

Extends EllipticCurvePrivateKey.

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 or DER), format ( TraditionalOpenSSL 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.EllipticCurvePublicKey[source]

New in version 0.5.

An elliptic curve public key.

verifier(signature, signature_algorithm)[source]

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

param bytes signature:
 The signature to verify. DER encoded as specified in RFC 3279.
param signature_algorithm:
 An instance of EllipticCurveSignatureAlgorithm.
returns:AsymmetricVerificationContext
curve
Type:EllipticCurve

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 to bytes. Encoding ( PEM or DER) and format ( SubjectPublicKeyInfo) are chosen to define the exact serialization.

Parameters:
Return bytes:

Serialized key.

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

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

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.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]
'-----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]
'-----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,
...    backend=default_backend()
...    )

>>> loaded_private_key = serialization.load_pem_private_key(
...    serialized_private,
...    password=b'testpassword',  # or password=None, if in plain text
...    backend=default_backend()
...    )

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.

RSA

RSA is a public-key algorithm for encrypting and signing messages.

Generation

Unlike symmetric cryptography, where the key is typically just a random series of bytes, RSA keys have a complex internal structure with specific mathematical properties.

cryptography.hazmat.primitives.asymmetric.rsa.generate_private_key(public_exponent, key_size, backend)[source]

New in version 0.5.

Generates a new RSA private key using the provided backend. key_size describes how many bits long the key should be, larger keys provide more security, currently 1024 and below are considered breakable, and 2048 or 4096 are reasonable default key sizes for new keys. The public_exponent indicates what one mathematical property of the key generation will be, 65537 should almost always be used.

>>> from cryptography.hazmat.backends import default_backend
>>> from cryptography.hazmat.primitives.asymmetric import rsa
>>> private_key = rsa.generate_private_key(
...     public_exponent=65537,
...     key_size=2048,
...     backend=default_backend()
... )
Parameters:
  • public_exponent (int) – The public exponent of the new key. Usually one of the small Fermat primes 3, 5, 17, 257, 65537. If in doubt you should use 65537.
  • key_size (int) – The length of the modulus in bits. For keys generated in 2015 it is strongly recommended to be at least 2048 (See page 41). It must not be less than 512. Some backends may have additional limitations.
  • backend – A backend which implements RSABackend.
Returns:

An instance of RSAPrivateKey.

Raises:

cryptography.exceptions.UnsupportedAlgorithm – This is raised if the provided backend does not implement RSABackend

Key loading

If you already have an on-disk key in the PEM format (which are recognizable by the distinctive -----BEGIN {format}----- and -----END {format}----- markers), you can load it:

>>> from cryptography.hazmat.primitives import serialization

>>> with open("path/to/key.pem", "rb") as key_file:
...     private_key = serialization.load_pem_private_key(
...         key_file.read(),
...         password=None,
...         backend=default_backend()
...     )

Serialized keys may optionally be encrypted on disk using a password. In this example we loaded an unencrypted key, and therefore we did not provide a password. If the key is encrypted we can pass a bytes object as the password argument.

There is also support for loading public keys in the SSH format.

Key serialization

If you have a private key that you’ve loaded or generated which implements the RSAPrivateKeyWithSerialization interface you can use private_bytes() to serialize the key.

>>> from cryptography.hazmat.primitives import serialization
>>> pem = private_key.private_bytes(
...    encoding=serialization.Encoding.PEM,
...    format=serialization.PrivateFormat.PKCS8,
...    encryption_algorithm=serialization.BestAvailableEncryption(b'mypassword')
... )
>>> pem.splitlines()[0]
'-----BEGIN ENCRYPTED PRIVATE KEY-----'

It is also possible to serialize without encryption using NoEncryption.

>>> pem = private_key.private_bytes(
...    encoding=serialization.Encoding.PEM,
...    format=serialization.PrivateFormat.TraditionalOpenSSL,
...    encryption_algorithm=serialization.NoEncryption()
... )
>>> pem.splitlines()[0]
'-----BEGIN RSA PRIVATE KEY-----'

For public keys you can use public_bytes() to serialize the key.

>>> from cryptography.hazmat.primitives import serialization
>>> public_key = private_key.public_key()
>>> pem = public_key.public_bytes(
...    encoding=serialization.Encoding.PEM,
...    format=serialization.PublicFormat.SubjectPublicKeyInfo
... )
>>> pem.splitlines()[0]
'-----BEGIN PUBLIC KEY-----'
Signing

A private key can be used to sign a message. This allows anyone with the public key to verify that the message was created by someone who possesses the corresponding private key. RSA signatures require a specific hash function, and padding to be used. Here is an example of signing message using RSA, with a secure hash function and padding:

>>> from cryptography.hazmat.primitives import hashes
>>> from cryptography.hazmat.primitives.asymmetric import padding

>>> signer = private_key.signer(
...     padding.PSS(
...         mgf=padding.MGF1(hashes.SHA256()),
...         salt_length=padding.PSS.MAX_LENGTH
...     ),
...     hashes.SHA256()
... )
>>> message = b"A message I want to sign"
>>> signer.update(message)
>>> signature = signer.finalize()

There is a shortcut to sign sufficiently short messages directly:

>>> message = b"A message I want to sign"
>>> signature = private_key.sign(
...     message,
...     padding.PSS(
...         mgf=padding.MGF1(hashes.SHA256()),
...         salt_length=padding.PSS.MAX_LENGTH
...     ),
...     hashes.SHA256()
... )

Valid paddings for signatures are PSS and PKCS1v15. PSS is the recommended choice for any new protocols or applications, PKCS1v15 should only be used to support legacy protocols.

Verification

The previous section describes what to do if you have a private key and want to sign something. If you have a public key, a message, a signature, and the signing algorithm that was used you can check that the private key associated with a given public key was used to sign that specific message. You can obtain a public key to use in verification using load_pem_public_key(), load_der_public_key(), public_key() , or public_key().

>>> public_key = private_key.public_key()
>>> verifier = public_key.verifier(
...     signature,
...     padding.PSS(
...         mgf=padding.MGF1(hashes.SHA256()),
...         salt_length=padding.PSS.MAX_LENGTH
...     ),
...     hashes.SHA256()
... )
>>> verifier.update(message)
>>> verifier.verify()

If the signature does not match, verify() will raise an InvalidSignature exception.

There is a shortcut to verify sufficiently short messages directly:

>>> public_key.verify(
...     signature,
...     message,
...     padding.PSS(
...         mgf=padding.MGF1(hashes.SHA256()),
...         salt_length=padding.PSS.MAX_LENGTH
...     ),
...     hashes.SHA256()
... )
Encryption

RSA encryption is interesting because encryption is performed using the public key, meaning anyone can encrypt data. The data is then decrypted using the private key.

Like signatures, RSA supports encryption with several different padding options. Here’s an example using a secure padding and hash function:

>>> message = b"encrypted data"
>>> ciphertext = public_key.encrypt(
...     message,
...     padding.OAEP(
...         mgf=padding.MGF1(algorithm=hashes.SHA1()),
...         algorithm=hashes.SHA1(),
...         label=None
...     )
... )

Valid paddings for encryption are OAEP and PKCS1v15. OAEP is the recommended choice for any new protocols or applications, PKCS1v15 should only be used to support legacy protocols.

Decryption

Once you have an encrypted message, it can be decrypted using the private key:

>>> plaintext = private_key.decrypt(
...     ciphertext,
...     padding.OAEP(
...         mgf=padding.MGF1(algorithm=hashes.SHA1()),
...         algorithm=hashes.SHA1(),
...         label=None
...     )
... )
>>> plaintext == message
True
Padding
class cryptography.hazmat.primitives.asymmetric.padding.AsymmetricPadding[source]

New in version 0.2.

name
class cryptography.hazmat.primitives.asymmetric.padding.PSS(mgf, salt_length)[source]

New in version 0.3.

Changed in version 0.4: Added salt_length parameter.

PSS (Probabilistic Signature Scheme) is a signature scheme defined in RFC 3447. It is more complex than PKCS1 but possesses a security proof. This is the recommended padding algorithm for RSA signatures. It cannot be used with RSA encryption.

Parameters:
  • mgf – A mask generation function object. At this time the only supported MGF is MGF1.
  • salt_length (int) – The length of the salt. It is recommended that this be set to PSS.MAX_LENGTH.
MAX_LENGTH

Pass this attribute to salt_length to get the maximum salt length available.

class cryptography.hazmat.primitives.asymmetric.padding.OAEP(mgf, algorithm, label)[source]

New in version 0.4.

OAEP (Optimal Asymmetric Encryption Padding) is a padding scheme defined in RFC 3447. It provides probabilistic encryption and is proven secure against several attack types. This is the recommended padding algorithm for RSA encryption. It cannot be used with RSA signing.

Parameters:
  • mgf – A mask generation function object. At this time the only supported MGF is MGF1.
  • algorithm – An instance of HashAlgorithm.
  • label (bytes) – A label to apply. This is a rarely used field and should typically be set to None or b"", which are equivalent.
class cryptography.hazmat.primitives.asymmetric.padding.PKCS1v15[source]

New in version 0.3.

PKCS1 v1.5 (also known as simply PKCS1) is a simple padding scheme developed for use with RSA keys. It is defined in RFC 3447. This padding can be used for signing and encryption.

It is not recommended that PKCS1v15 be used for new applications, OAEP should be preferred for encryption and PSS should be preferred for signatures.

cryptography.hazmat.primitives.asymmetric.padding.calculate_max_pss_salt_length(key, hash_algorithm)[source]

New in version 1.5.

Parameters:
Returns int:

The computed salt length.

Computes the length of the salt that PSS will use if PSS.MAX_LENGTH is used.

Mask generation functions
class cryptography.hazmat.primitives.asymmetric.padding.MGF1(algorithm)[source]

New in version 0.3.

Changed in version 0.6: Removed the deprecated salt_length parameter.

MGF1 (Mask Generation Function 1) is used as the mask generation function in PSS and OAEP padding. It takes a hash algorithm.

Parameters:algorithm – An instance of HashAlgorithm.
Numbers

These classes hold the constituent components of an RSA key. They are useful only when more traditional Key Serialization is unavailable.

class cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicNumbers(e, n)[source]

New in version 0.5.

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

n
Type:int

The public modulus.

e
Type:int

The public exponent.

public_key(backend)[source]
Parameters:backend – An instance of RSABackend.
Returns:A new instance of RSAPublicKey.
class cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateNumbers(p, q, d, dmp1, dmq1, iqmp, public_numbers)[source]

New in version 0.5.

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

Warning

With the exception of the integers contained in the RSAPublicNumbers all attributes of this class must be kept secret. Revealing them will compromise the security of any cryptographic operations performed with a key loaded from them.

public_numbers
Type:RSAPublicNumbers

The RSAPublicNumbers which makes up the RSA public key associated with this RSA private key.

p
Type:int

p, one of the two primes composing n.

q
Type:int

q, one of the two primes composing n.

d
Type:int

The private exponent.

dmp1
Type:int

A Chinese remainder theorem coefficient used to speed up RSA operations. Calculated as: d mod (p-1)

dmq1
Type:int

A Chinese remainder theorem coefficient used to speed up RSA operations. Calculated as: d mod (q-1)

iqmp
Type:int

A Chinese remainder theorem coefficient used to speed up RSA operations. Calculated as: q-1 mod p

private_key(backend)[source]
Parameters:backend – A new instance of RSABackend.
Returns:An instance of RSAPrivateKey.
Handling partial RSA private keys

If you are trying to load RSA private keys yourself you may find that not all parameters required by RSAPrivateNumbers are available. In particular the Chinese Remainder Theorem (CRT) values dmp1, dmq1, iqmp may be missing or present in a different form. For example, OpenPGP does not include the iqmp, dmp1 or dmq1 parameters.

The following functions are provided for users who want to work with keys like this without having to do the math themselves.

cryptography.hazmat.primitives.asymmetric.rsa.rsa_crt_iqmp(p, q)[source]

New in version 0.4.

Computes the iqmp (also known as qInv) parameter from the RSA primes p and q.

cryptography.hazmat.primitives.asymmetric.rsa.rsa_crt_dmp1(private_exponent, p)[source]

New in version 0.4.

Computes the dmp1 parameter from the RSA private exponent (d) and prime p.

cryptography.hazmat.primitives.asymmetric.rsa.rsa_crt_dmq1(private_exponent, q)[source]

New in version 0.4.

Computes the dmq1 parameter from the RSA private exponent (d) and prime q.

cryptography.hazmat.primitives.asymmetric.rsa.rsa_recover_prime_factors(n, e, d)[source]

New in version 0.8.

Computes the prime factors (p, q) given the modulus, public exponent, and private exponent.

Note

When recovering prime factors this algorithm will always return p and q such that p > q. Note: before 1.5, this function always returned p and q such that p < q. It was changed because libraries commonly require p > q.

Returns:A tuple (p, q)
Key interfaces
class cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey[source]

New in version 0.2.

An RSA private key.

signer(padding, algorithm)[source]

New in version 0.3.

Get signer to sign data which can be verified later by others using the public key.

Parameters:
Returns:

AsymmetricSignatureContext

decrypt(ciphertext, padding)[source]

New in version 0.4.

Decrypt data that was encrypted with the public key.

Parameters:
Return bytes:

Decrypted data.

public_key()[source]
Returns:RSAPublicKey

An RSA public key object corresponding to the values of the private key.

key_size
Type:int

The bit length of the modulus.

sign(data, padding, algorithm)[source]

New in version 1.4.

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

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

Parameters:
Return bytes:

Signature.

class cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKeyWithSerialization[source]

New in version 0.8.

Extends RSAPrivateKey.

private_numbers()[source]

Create a RSAPrivateNumbers object.

Returns:An RSAPrivateNumbers instance.
private_bytes(encoding, format, encryption_algorithm)[source]

Allows serialization of the key to bytes. Encoding ( PEM or DER), format ( TraditionalOpenSSL 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.rsa.RSAPublicKey[source]

New in version 0.2.

An RSA public key.

verifier(signature, padding, algorithm)[source]

New in version 0.3.

Get verifier to verify data was signed by the private key associated with this public key.

Parameters:
Returns:

AsymmetricVerificationContext

encrypt(plaintext, padding)[source]

New in version 0.4.

Encrypt data with the public key.

Parameters:
Return bytes:

Encrypted data.

key_size
Type:int

The bit length of the modulus.

public_numbers()[source]

Create a RSAPublicNumbers object.

Returns:An RSAPublicNumbers instance.
public_bytes(encoding, format)[source]

Allows serialization of the key to bytes. Encoding ( PEM or DER) and format ( SubjectPublicKeyInfo or PKCS1) are chosen to define the exact serialization.

Parameters:
Return bytes:

Serialized key.

verify(signature, data, padding, algorithm)[source]

New in version 1.4.

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

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

Parameters:
  • signature (bytes) – The signature to verify.
  • data (bytes) – The message string that was signed.
  • padding – An instance of AsymmetricPadding.
  • algorithm – An instance of HashAlgorithm or Prehashed if the data you want to sign has already been hashed.
Raises:

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

class cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKeyWithSerialization

New in version 0.8.

Alias for RSAPublicKey.

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.

Diffie-Hellman key exchange

Diffie-Hellman key exchange (D–H) is a method that allows two parties to jointly agree on a shared secret using an insecure channel.

Exchange Algorithm

For most applications the shared_key should be passed to a key derivation function.

>>> from cryptography.hazmat.backends import default_backend
>>> from cryptography.hazmat.primitives.asymmetric import dh
>>> parameters = dh.generate_parameters(generator=2, key_size=2048,
...                                     backend=default_backend())
>>> private_key = parameters.generate_private_key()
>>> peer_public_key = parameters.generate_private_key().public_key()
>>> shared_key = private_key.exchange(peer_public_key)

DHE (or EDH), the ephemeral form of this exchange, is strongly preferred over simple DH and provides forward secrecy when used. You must generate a new private key using generate_private_key() for each exchange() when performing an DHE key exchange.

To assemble a DHParameters and a DHPublicKey from primitive integers, you must first create the DHParameterNumbers and DHPublicNumbers objects. For example, if p, g, and y are int objects received from a peer:

pn = dh.DHParameterNumbers(p, g)
parameters = pn.parameters(default_backend())
peer_public_numbers = dh.DHPublicNumbers(y, pn)
peer_public_key = peer_public_numbers.public_key(default_backend())

See also the DHBackend API for additional functionality.

Group parameters
cryptography.hazmat.primitives.asymmetric.dh.generate_parameters(generator, key_size, backend)[source]

New in version 0.9.

Generate a new DH parameter group for use with backend.

Parameters:
  • generator – The int to use as a generator. Must be 2 or 5.
  • key_size – The bit length of the prime modulus to generate.
  • backend – A DHBackend instance.
Returns:

DH parameters as a new instance of DHParameters.

Raises:

ValueError – If key_size is not at least 512.

class cryptography.hazmat.primitives.asymmetric.dh.DHParameters[source]

New in version 0.9.

generate_private_key()[source]

New in version 0.9.

Generate a DH private key. This method can be used to generate many new private keys from a single set of parameters.

Returns:An instance of DHPrivateKey.
class cryptography.hazmat.primitives.asymmetric.dh.DHParametersWithSerialization[source]

New in version 0.9.

Inherits from DHParameters.

parameter_numbers()[source]

Return the numbers that make up this set of parameters.

Returns:A DHParameterNumbers.
Key interfaces
class cryptography.hazmat.primitives.asymmetric.dh.DHPrivateKey[source]

New in version 0.9.

key_size

The bit length of the prime modulus.

public_key()[source]

Return the public key associated with this private key.

Returns:A DHPublicKey.
parameters()[source]

Return the parameters associated with this private key.

Returns:A DHParameters.
class cryptography.hazmat.primitives.asymmetric.dh.DHPrivateKeyWithSerialization[source]

New in version 0.9.

Inherits from DHPrivateKey.

private_numbers()[source]

Return the numbers that make up this private key.

Returns:A DHPrivateNumbers.
exchange(peer_public_key)[source]

New in version 1.7.

Parameters:peer_public_key (DHPublicKeyWithSerialization) – The public key for the peer.
Return bytes:The agreed key. The bytes are ordered in ‘big’ endian.
private_bytes(encoding, format, encryption_algorithm)

New in version 1.8.

Allows serialization of the key to bytes. Encoding ( PEM or DER), format ( 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.dh.DHPublicKey[source]

New in version 0.9.

key_size

The bit length of the prime modulus.

parameters()[source]

Return the parameters associated with this private key.

Returns:A DHParameters.
class cryptography.hazmat.primitives.asymmetric.dh.DHPublicKeyWithSerialization[source]

New in version 0.9.

Inherits from DHPublicKey.

public_numbers()[source]

Return the numbers that make up this public key.

Returns:A DHPublicNumbers.
public_bytes(encoding, format)

New in version 1.8.

Allows serialization of the key to bytes. Encoding ( PEM or DER) and format ( SubjectPublicKeyInfo) are chosen to define the exact serialization.

Parameters:
Return bytes:

Serialized key.

Numbers
class cryptography.hazmat.primitives.asymmetric.dh.DHParameterNumbers(p, g, q=None)[source]

New in version 0.8.

The collection of integers that define a Diffie-Hellman group.

p
Type:int

The prime modulus value.

g
Type:int

The generator value. Must be 2 or 5 (Unless q is given).

q

New in version 1.8.

Type:int

p subgroup order value.

class cryptography.hazmat.primitives.asymmetric.dh.DHPrivateNumbers(x, public_numbers)[source]

New in version 0.8.

The collection of integers that make up a Diffie-Hellman private key.

public_numbers
Type:DHPublicNumbers

The DHPublicNumbers which makes up the DH public key associated with this DH private key.

x
Type:int

The private value.

class cryptography.hazmat.primitives.asymmetric.dh.DHPublicNumbers(y, parameter_numbers)[source]

New in version 0.8.

The collection of integers that make up a Diffie-Hellman public key.

parameter_numbers
Type:DHParameterNumbers

The parameters for this DH group.

y
Type:int

The public value.

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.

Key Serialization

There are several common schemes for serializing asymmetric private and public keys to bytes. They generally support encryption of private keys and additional key metadata.

Many serialization formats support multiple different types of asymmetric keys and will return an instance of the appropriate type. You should check that the returned key matches the type your application expects when using these methods.

>>> from cryptography.hazmat.backends import default_backend
>>> from cryptography.hazmat.primitives.asymmetric import dsa, rsa
>>> from cryptography.hazmat.primitives.serialization import load_pem_private_key
>>> key = load_pem_private_key(pem_data, password=None, backend=default_backend())
>>> if isinstance(key, rsa.RSAPrivateKey):
...     signature = sign_with_rsa_key(key, message)
... elif isinstance(key, dsa.DSAPrivateKey):
...     signature = sign_with_dsa_key(key, message)
... else:
...     raise TypeError
Key dumping

The serialization module contains functions for loading keys from bytes. To dump a key object to bytes, you must call the appropriate bytes on the key object. Documentation for these methods in found in the rsa, dsa, and ec module documentation.

PEM

PEM is an encapsulation format, meaning keys in it can actually be any of several different key types. However these are all self-identifying, so you don’t need to worry about this detail. PEM keys are recognizable because they all begin with -----BEGIN {format}----- and end with -----END {format}-----.

Note

A PEM block which starts with -----BEGIN CERTIFICATE----- is not a public or private key, it’s an X.509 Certificate. You can load it using load_pem_x509_certificate() and extract the public key with Certificate.public_key.

cryptography.hazmat.primitives.serialization.load_pem_private_key(data, password, backend)[source]

New in version 0.6.

Deserialize a private key from PEM encoded data to one of the supported asymmetric private key types.

Parameters:
  • data (bytes) – The PEM encoded key data.
  • password (bytes) – The password to use to decrypt the data. Should be None if the private key is not encrypted.
  • backend – An instance of PEMSerializationBackend.
Returns:

One of RSAPrivateKey, DSAPrivateKey, or EllipticCurvePrivateKey depending on the contents of data.

Raises:
  • ValueError – If the PEM data could not be decrypted or if its structure could not be decoded successfully.
  • TypeError – If a password was given and the private key was not encrypted. Or if the key was encrypted but no password was supplied.
  • cryptography.exceptions.UnsupportedAlgorithm – If the serialized key is of a type that is not supported by the backend or if the key is encrypted with a symmetric cipher that is not supported by the backend.
cryptography.hazmat.primitives.serialization.load_pem_public_key(data, backend)[source]

New in version 0.6.

Deserialize a public key from PEM encoded data to one of the supported asymmetric public key types. The PEM encoded data is typically a subjectPublicKeyInfo payload as specified in RFC 5280.

>>> from cryptography.hazmat.primitives.serialization import load_pem_public_key
>>> key = load_pem_public_key(public_pem_data, backend=default_backend())
>>> isinstance(key, rsa.RSAPublicKey)
True
Parameters:
Returns:

One of RSAPublicKey, DSAPublicKey, or EllipticCurvePublicKey depending on the contents of data.

Raises:
DER

DER is an ASN.1 encoding type. There are no encapsulation boundaries and the data is binary. DER keys may be in a variety of formats, but as long as you know whether it is a public or private key the loading functions will handle the rest.

cryptography.hazmat.primitives.serialization.load_der_private_key(data, password, backend)[source]

New in version 0.8.

Deserialize a private key from DER encoded data to one of the supported asymmetric private key types.

Parameters:
  • data (bytes) – The DER encoded key data.
  • password (bytes) – The password to use to decrypt the data. Should be None if the private key is not encrypted.
  • backend – An instance of DERSerializationBackend.
Returns:

One of RSAPrivateKey, DSAPrivateKey, or EllipticCurvePrivateKey depending on the contents of data.

Raises:
  • ValueError – If the DER data could not be decrypted or if its structure could not be decoded successfully.
  • TypeError – If a password was given and the private key was not encrypted. Or if the key was encrypted but no password was supplied.
  • cryptography.exceptions.UnsupportedAlgorithm – If the serialized key is of a type that is not supported by the backend or if the key is encrypted with a symmetric cipher that is not supported by the backend.
>>> from cryptography.hazmat.backends import default_backend
>>> from cryptography.hazmat.primitives.asymmetric import rsa
>>> from cryptography.hazmat.primitives.serialization import load_der_private_key
>>> key = load_der_private_key(der_data, password=None, backend=default_backend())
>>> isinstance(key, rsa.RSAPrivateKey)
True
cryptography.hazmat.primitives.serialization.load_der_public_key(data, backend)[source]

New in version 0.8.

Deserialize a public key from DER encoded data to one of the supported asymmetric public key types. The DER encoded data is typically a subjectPublicKeyInfo payload as specified in RFC 5280.

Parameters:
Returns:

One of RSAPublicKey, DSAPublicKey, or EllipticCurvePublicKey depending on the contents of data.

Raises:
>>> from cryptography.hazmat.backends import default_backend
>>> from cryptography.hazmat.primitives.asymmetric import rsa
>>> from cryptography.hazmat.primitives.serialization import load_der_public_key
>>> key = load_der_public_key(public_der_data, backend=default_backend())
>>> isinstance(key, rsa.RSAPublicKey)
True
OpenSSH Public Key

The format used by OpenSSH to store public keys, as specified in RFC 4253.

An example RSA key in OpenSSH format (line breaks added for formatting purposes):

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDDu/XRP1kyK6Cgt36gts9XAk
FiiuJLW6RU0j3KKVZSs1I7Z3UmU9/9aVh/rZV43WQG8jaR6kkcP4stOR0DEtll
PDA7ZRBnrfiHpSQYQ874AZaAoIjgkv7DBfsE6gcDQLub0PFjWyrYQUJhtOLQEK
vY/G0vt2iRL3juawWmCFdTK3W3XvwAdgGk71i6lHt+deOPNEPN2H58E4odrZ2f
sxn/adpDqfb2sM0kPwQs0aWvrrKGvUaustkivQE4XWiSFnB0oJB/lKK/CKVKuy
///ImSCGHQRvhwariN2tvZ6CBNSLh3iQgeB0AkyJlng7MXB2qYq/Ci2FUOryCX
2MzHvnbv testkey@localhost

DSA keys look almost identical but begin with ssh-dss rather than ssh-rsa. ECDSA keys have a slightly different format, they begin with ecdsa-sha2-{curve}.

cryptography.hazmat.primitives.serialization.load_ssh_public_key(data, backend)[source]

New in version 0.7.

Deserialize a public key from OpenSSH (RFC 4253) encoded data to an instance of the public key type for the specified backend.

Note

Currently Ed25519 keys are not supported.

Parameters:
Returns:

One of RSAPublicKey, DSAPublicKey, or EllipticCurvePublicKey depending on the contents of data.

Raises:
Serialization Formats
class cryptography.hazmat.primitives.serialization.PrivateFormat[source]

New in version 0.8.

An enumeration for private key formats. Used with the private_bytes method available on RSAPrivateKeyWithSerialization , EllipticCurvePrivateKeyWithSerialization and DSAPrivateKeyWithSerialization.

TraditionalOpenSSL

Frequently known as PKCS#1 format. Still a widely used format, but generally considered legacy.

PKCS8

A more modern format for serializing keys which allows for better encryption. Choose this unless you have explicit legacy compatibility requirements.

class cryptography.hazmat.primitives.serialization.PublicFormat[source]

New in version 0.8.

An enumeration for public key formats. Used with the public_bytes method available on RSAPublicKeyWithSerialization , EllipticCurvePublicKeyWithSerialization , and DSAPublicKeyWithSerialization.

SubjectPublicKeyInfo

This is the typical public key format. It consists of an algorithm identifier and the public key as a bit string. Choose this unless you have specific needs.

PKCS1

Just the public key elements (without the algorithm identifier). This format is RSA only, but is used by some older systems.

OpenSSH

New in version 1.4.

The public key format used by OpenSSH (e.g. as found in ~/.ssh/id_rsa.pub or ~/.ssh/authorized_keys).

Serialization Encodings
class cryptography.hazmat.primitives.serialization.Encoding[source]

An enumeration for encoding types. Used with the private_bytes method available on RSAPrivateKeyWithSerialization , EllipticCurvePrivateKeyWithSerialization and DSAPrivateKeyWithSerialization as well as public_bytes on RSAPublicKeyWithSerialization and EllipticCurvePublicKeyWithSerialization.

PEM

New in version 0.8.

For PEM format. This is a base64 format with delimiters.

DER

New in version 0.9.

For DER format. This is a binary format.

OpenSSH

New in version 1.4.

The format used by OpenSSH public keys. This is a text format.

Serialization Encryption Types
class cryptography.hazmat.primitives.serialization.KeySerializationEncryption[source]

Objects with this interface are usable as encryption types with methods like private_bytes available on RSAPrivateKeyWithSerialization , EllipticCurvePrivateKeyWithSerialization and DSAPrivateKeyWithSerialization. All other classes in this section represent the available choices for encryption and have this interface. They are used with private_bytes.

class cryptography.hazmat.primitives.serialization.BestAvailableEncryption(password)[source]

Encrypt using the best available encryption for a given key’s backend. This is a curated encryption choice and the algorithm may change over time.

Parameters:password (bytes) – The password to use for encryption.
class cryptography.hazmat.primitives.serialization.NoEncryption[source]

Do not encrypt.

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.

Signature Interfaces
class cryptography.hazmat.primitives.asymmetric.AsymmetricSignatureContext[source]

New in version 0.2.

update(data)[source]
Parameters:data (bytes) – The data you want to sign.
finalize()[source]
Return bytes signature:
 The signature.
class cryptography.hazmat.primitives.asymmetric.AsymmetricVerificationContext[source]

New in version 0.2.

update(data)[source]
Parameters:data (bytes) – The data you wish to verify using the signature.
verify()[source]
Raises:cryptography.exceptions.InvalidSignature – If the signature does not validate.

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.

Asymmetric Utilities
cryptography.hazmat.primitives.asymmetric.utils.decode_dss_signature(signature)[source]

Takes in signatures generated by the DSA/ECDSA signers and returns a tuple (r, s). These signatures are ASN.1 encoded Dss-Sig-Value sequences (as defined in RFC 3279)

Parameters:signature (bytes) – The signature to decode.
Returns:The decoded tuple (r, s).
Raises:ValueError – Raised if the signature is malformed.
cryptography.hazmat.primitives.asymmetric.utils.encode_dss_signature(r, s)[source]

Creates an ASN.1 encoded Dss-Sig-Value (as defined in RFC 3279) from raw r and s values.

Parameters:
  • r (int) – The raw signature value r.
  • s (int) – The raw signature value s.
Return bytes:

The encoded signature.

class cryptography.hazmat.primitives.asymmetric.utils.Prehashed(algorithm)[source]

New in version 1.6.

Prehashed can be passed as the algorithm in the RSA sign() and verify() as well as DSA sign() and verify() methods.

For elliptic curves it can be passed as the algorithm in ECDSA and then used with sign() and verify() .

Parameters:algorithm – An instance of HashAlgorithm.
>>> import hashlib
>>> from cryptography.hazmat.backends import default_backend
>>> from cryptography.hazmat.primitives import hashes
>>> from cryptography.hazmat.primitives.asymmetric import (
...    padding, rsa, utils
... )
>>> private_key = rsa.generate_private_key(
...     public_exponent=65537,
...     key_size=2048,
...     backend=default_backend()
... )
>>> prehashed_msg = hashlib.sha256