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 method 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, DHPrivateKey, 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, DHPublicKey, or EllipticCurvePublicKey depending on the contents of data.

Raises:
cryptography.hazmat.primitives.serialization.load_pem_parameters(data, backend)[source]

New in version 2.0.

Deserialize parameters from PEM encoded data to one of the supported asymmetric parameters types.

>>> from cryptography.hazmat.primitives.serialization import load_pem_parameters
>>> from cryptography.hazmat.primitives.asymmetric import dh
>>> parameters = load_pem_parameters(parameters_pem_data, backend=default_backend())
>>> isinstance(parameters, dh.DHParameters)
True
Parameters:
Returns:

Currently only DHParameters supported.

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, DHPrivateKey, 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, DHPublicKey, 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
cryptography.hazmat.primitives.serialization.load_der_parameters(data, backend)[source]

New in version 2.0.

Deserialize parameters from DER encoded data to one of the supported asymmetric parameters types.

Parameters:
Returns:

Currently only DHParameters supported.

Raises:
>>> from cryptography.hazmat.backends import default_backend
>>> from cryptography.hazmat.primitives.asymmetric import dh
>>> from cryptography.hazmat.primitives.serialization import load_der_parameters
>>> parameters = load_der_parameters(parameters_der_data, backend=default_backend())
>>> isinstance(parameters, dh.DHParameters)
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 , DHPrivateKeyWithSerialization and DSAPrivateKeyWithSerialization.

TraditionalOpenSSL

Frequently known as PKCS#1 format. Still a widely used format, but generally considered legacy.

A PEM encoded RSA key will look like:

-----BEGIN RSA PRIVATE KEY-----
...
-----END RSA PRIVATE KEY-----
PKCS8

A more modern format for serializing keys which allows for better encryption. Choose this unless you have explicit legacy compatibility requirements.

A PEM encoded key will look like:

-----BEGIN PRIVATE KEY-----
...
-----END PRIVATE KEY-----
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 , DHPublicKeyWithSerialization , 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.

A PEM encoded key will look like:

-----BEGIN PUBLIC KEY-----
...
-----END PUBLIC KEY-----
PKCS1

Just the public key elements (without the algorithm identifier). This format is RSA only, but is used by some older systems.

A PEM encoded key will look like:

-----BEGIN RSA PUBLIC KEY-----
...
-----END RSA PUBLIC KEY-----
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).

class cryptography.hazmat.primitives.serialization.ParameterFormat[source]

New in version 2.0.

An enumeration for parameters formats. Used with the parameter_bytes method available on DHParametersWithSerialization.

PKCS3

ASN1 DH parameters sequence as defined in PKCS3.

Serialization Encodings

class cryptography.hazmat.primitives.serialization.Encoding[source]

An enumeration for encoding types. Used with the private_bytes method available on RSAPrivateKeyWithSerialization , EllipticCurvePrivateKeyWithSerialization , DHPrivateKeyWithSerialization and DSAPrivateKeyWithSerialization as well as public_bytes on RSAPublicKeyWithSerialization, DHPublicKeyWithSerialization 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 , DHPrivateKeyWithSerialization 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.