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.primitives.asymmetric import dsa, rsa
>     >>> from cryptography.hazmat.primitives.serialization import load_pem_private_key
>     >>> key = load_pem_private_key(pem_data, password=None)
>     >>> 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, *, unsafe_skip_rsa_key_validation=False)

  Added in version 0.6.

  Note

  SSH private keys are a different format and must be loaded with `load_ssh_private_key()`.

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

  Parameters:

    - data (bytes-like) – The PEM encoded key data.

    - password (bytes-like) – The password to use to decrypt the data. Should be `None` if the private key is not encrypted.

    - unsafe_skip_rsa_key_validation (bool) –

      Added in version 39.0.0.

      A keyword-only argument that defaults to `False`. If `True` RSA private keys will not be validated. This significantly speeds up loading the keys, but is unsafe unless you are certain the key is valid. User supplied keys should never be loaded with this parameter set to `True`. If you do load an invalid key this way and attempt to use it OpenSSL may hang, crash, or otherwise misbehave.

  Returns:

    One of `Ed25519PrivateKey`, `X25519PrivateKey`, `Ed448PrivateKey`, `X448PrivateKey`, `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 type is not supported by the OpenSSL version `cryptography` is using.

cryptography.hazmat.primitives.serialization.load_pem_public_key(data)

  Added 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)
      >>> isinstance(key, rsa.RSAPublicKey)
      True

  Parameters:

    data (bytes) – The PEM encoded key data.

  Returns:

    One of `Ed25519PublicKey`, `X25519PublicKey`, `Ed448PublicKey`, `X448PublicKey`, `RSAPublicKey`, `DSAPublicKey`, `DHPublicKey`, or `EllipticCurvePublicKey` depending on the contents of `data`.

  Raises:

    - ValueError – If the PEM data’s structure could not be decoded successfully.

    - cryptography.exceptions.UnsupportedAlgorithm – If the serialized key type is not supported by the OpenSSL version `cryptography` is using.

cryptography.hazmat.primitives.serialization.load_pem_parameters(data)
.. versionadded:: 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)
      >>> isinstance(parameters, dh.DHParameters)
      True

  Parameters:

    data (bytes) – The PEM encoded parameters data.

  Returns:

    Currently only `DHParameters` supported.

  Raises:

    - ValueError – If the PEM data’s structure could not be decoded successfully.

    - cryptography.exceptions.UnsupportedAlgorithm – If the serialized key type is not supported by the OpenSSL version `cryptography` is using.

## 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, *, unsafe_skip_rsa_key_validation=False)

  Added in version 0.8.

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

  Parameters:

    - data (bytes-like) – The DER encoded key data.

    - password (bytes-like) – The password to use to decrypt the data. Should be `None` if the private key is not encrypted.

    - unsafe_skip_rsa_key_validation (bool) –

      Added in version 39.0.0.

      A keyword-only argument that defaults to `False`. If `True` RSA private keys will not be validated. This significantly speeds up loading the keys, but is unsafe unless you are certain the key is valid. User supplied keys should never be loaded with this parameter set to `True`. If you do load an invalid key this way and attempt to use it OpenSSL may hang, crash, or otherwise misbehave.

  Returns:

    One of `Ed25519PrivateKey`, `X25519PrivateKey`, `Ed448PrivateKey`, `X448PrivateKey`, `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 type is not supported by the OpenSSL version `cryptography` is using.

      >>> 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)
      >>> isinstance(key, rsa.RSAPrivateKey)
      True

cryptography.hazmat.primitives.serialization.load_der_public_key(data)

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

    data (bytes) – The DER encoded key data.

  Returns:

    One of `Ed25519PublicKey`, `X25519PublicKey`, `Ed448PublicKey`, `X448PublicKey`, `RSAPublicKey`, `DSAPublicKey`, `DHPublicKey`, or `EllipticCurvePublicKey` depending on the contents of `data`.

  Raises:

    - ValueError – If the DER data’s structure could not be decoded successfully.

    - cryptography.exceptions.UnsupportedAlgorithm – If the serialized key type is not supported by the OpenSSL version `cryptography` is using.

      >>> 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)
      >>> isinstance(key, rsa.RSAPublicKey)
      True

cryptography.hazmat.primitives.serialization.load_der_parameters(data)

  Added in version 2.0.

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

  Parameters:

    data (bytes) – The DER encoded parameters data.

  Returns:

    Currently only `DHParameters` supported.

  Raises:

    - ValueError – If the DER data’s structure could not be decoded successfully.

    - cryptography.exceptions.UnsupportedAlgorithm – If the serialized key type is not supported by the OpenSSL version `cryptography` is using.

      >>> from cryptography.hazmat.primitives.asymmetric import dh
      >>> from cryptography.hazmat.primitives.serialization import load_der_parameters
      >>> parameters = load_der_parameters(parameters_der_data)
      >>> 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.SSHPublicKeyTypes

  Added in version 40.0.0.

  Type alias: A union of public key types accepted for SSH: `RSAPublicKey`, `DSAPublicKey`, `EllipticCurvePublicKey` , or `Ed25519PublicKey`.

cryptography.hazmat.primitives.serialization.load_ssh_public_key(data)

  Added in version 0.7.

  Note

  SSH DSA key support is deprecated and will be removed in a future release.

  Deserialize a public key from OpenSSH (RFC 4253 and PROTOCOL.certkeys) encoded data to an instance of the public key type.

  Parameters:

    data (bytes-like) – The OpenSSH encoded key data.

  Returns:

    One of `SSHPublicKeyTypes` depending on the contents of `data`.

  Raises:

    - ValueError – If the OpenSSH data could not be properly decoded or if the key is not in the proper format.

    - cryptography.exceptions.UnsupportedAlgorithm – If the serialized key is of a type that is not supported.

## OpenSSH Private Key

The format used by OpenSSH to store private keys, as approximately specified in PROTOCOL.key.

An example ECDSA key in OpenSSH format:

    -----BEGIN OPENSSH PRIVATE KEY-----
    b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAaAAAABNlY2RzYS
    1zaGEyLW5pc3RwMjU2AAAACG5pc3RwMjU2AAAAQQRI0fWnI1CxX7qYqp0ih6bxjhGmUrZK
    /Axf8vhM8Db3oH7CFR+JdL715lUdu4XCWvQZKVf60/h3kBFhuxQC23XjAAAAqKPzVaOj81
    WjAAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBEjR9acjULFfupiq
    nSKHpvGOEaZStkr8DF/y+EzwNvegfsIVH4l0vvXmVR27hcJa9BkpV/rT+HeQEWG7FALbde
    MAAAAga/VGV2asRlL3kXXao0aochQ59nXHA2xEGeAoQd952r0AAAAJbWFya29AdmZmAQID
    BAUGBw==
    -----END OPENSSH PRIVATE KEY-----

cryptography.hazmat.primitives.serialization.SSHPrivateKeyTypes

  Added in version 40.0.0.

  Type alias: A union of private key types accepted for SSH: `RSAPrivateKey`, `DSAPrivateKey`, `EllipticCurvePrivateKey` or `Ed25519PrivateKey`.

cryptography.hazmat.primitives.serialization.load_ssh_private_key(data, password)

  Added in version 3.0.

  Note

  SSH DSA key support is deprecated and will be removed in a future release.

  Deserialize a private key from OpenSSH encoded data to an instance of the private key type.

  Parameters:

    - data (bytes-like) – The PEM encoded OpenSSH private key data.

    - password (bytes) – Password bytes to use to decrypt password-protected key. Or `None` if not needed.

  Returns:

    One of `SSHPrivateKeyTypes` depending on the contents of `data`.

  Raises:

    - ValueError – If the OpenSSH data could not be properly decoded, if the key is not in the proper format or the incorrect password was provided.

    - cryptography.exceptions.UnsupportedAlgorithm – If the serialized key is of a type that is not supported.

## OpenSSH Certificate

The format used by OpenSSH for certificates, as specified in PROTOCOL.certkeys.

cryptography.hazmat.primitives.serialization.SSHCertPublicKeyTypes

  Added in version 40.0.0.

  Type alias: A union of public key types supported for SSH certificates: `RSAPublicKey`, `EllipticCurvePublicKey` or `Ed25519PublicKey`

cryptography.hazmat.primitives.serialization.SSHCertPrivateKeyTypes

  Added in version 40.0.0.

  Type alias: A union of private key types supported for SSH certificates: `RSAPrivateKey`, `EllipticCurvePrivateKey` or `Ed25519PrivateKey`

cryptography.hazmat.primitives.serialization.load_ssh_public_identity(data)

  Added in version 40.0.0.

  Note

  This function does not support parsing certificates with DSA public keys or signatures from DSA certificate authorities. DSA is a deprecated algorithm and should not be used.

  Deserialize an OpenSSH encoded identity to an instance of `SSHCertificate` or the appropriate public key type. Parsing a certificate does not verify anything. It is up to the caller to perform any necessary verification.

  Parameters:

    data (bytes) – The OpenSSH encoded data.

  Returns:

    `SSHCertificate` or one of `SSHCertPublicKeyTypes`.

  Raises:

    - ValueError – If the OpenSSH data could not be properly decoded.

    - cryptography.exceptions.UnsupportedAlgorithm – If the data contains a public key type that is not supported.

class cryptography.hazmat.primitives.serialization.SSHCertificate

  Added in version 40.0.0.

  nonce
    Type:

      bytes

    The nonce field is a CA-provided random value of arbitrary length (but typically 16 or 32 bytes) included to make attacks that depend on inducing collisions in the signature hash infeasible.

  public_key()

    The public key contained in the certificate, one of `SSHCertPublicKeyTypes`.

  serial
    Type:

      int

    Serial is an optional certificate serial number set by the CA to provide an abbreviated way to refer to certificates from that CA. If a CA does not wish to number its certificates, it must set this field to zero.

  type
    Type:

      `SSHCertificateType`

    Type specifies whether this certificate is for identification of a user or a host.

  key_id
    Type:

      bytes

    This is a free-form text field that is filled in by the CA at the time of signing; the intention is that the contents of this field are used to identify the identity principal in log messages.

  valid_principals
    Type:

      list[bytes]

    “valid principals” is a list containing one or more principals as byte strings. These principals list the names for which this certificate is valid; hostnames for host certificates and usernames for user certificates. As a special case, an empty list means the certificate is valid for any principal of the specified type.

  valid_after
    Type:

      int

    An integer representing the Unix timestamp (in UTC) after which the certificate is valid. This time is inclusive.

  valid_before
    Type:

      int

    An integer representing the Unix timestamp (in UTC) before which the certificate is valid. This time is not inclusive.

  critical_options
    Type:

      dict[bytes, bytes]

    Critical options is a dict of zero or more options that are critical for the certificate to be considered valid. If any of these options are not supported by the implementation, the certificate must be rejected.

  extensions
    Type:

      dict[bytes, bytes]

    Extensions is a dict of zero or more options that are non-critical for the certificate to be considered valid. If any of these options are not supported by the implementation, the implementation may safely ignore them.

  signature_key()

    The public key used to sign the certificate, one of `SSHCertPublicKeyTypes`.

  verify_cert_signature()

    Warning

    This method does not validate anything about whether the signing key is trusted! Callers are responsible for validating trust in the signer.

    Validates that the signature on the certificate was created by the private key associated with the certificate’s signature key and that the certificate has not been changed since signing.

    Returns:

      None

    Raises:

      `InvalidSignature` if the signature is invalid.

  public_bytes()
    Returns:

      The serialized certificate in OpenSSH format.

    Return type:

      bytes

class cryptography.hazmat.primitives.serialization.SSHCertificateType

  Added in version 40.0.0.

  An enumeration of the types of SSH certificates.

  USER

    The cert is intended for identification of a user. Corresponds to the value `1`.

  HOST

    The cert is intended for identification of a host. Corresponds to the value `2`.

## SSH Certificate Builder

class cryptography.hazmat.primitives.serialization.SSHCertificateBuilder

  Added in version 40.0.0.

  Note

  This builder does not support generating certificates with DSA public keys or creating signatures with DSA certificate authorities. DSA is a deprecated algorithm and should not be used.

      >>> import datetime
      >>> from cryptography.hazmat.primitives.asymmetric import ec
      >>> from cryptography.hazmat.primitives.serialization import (
      ...     SSHCertificateType, SSHCertificateBuilder
      ... )
      >>> signing_key = ec.generate_private_key(ec.SECP256R1())
      >>> public_key = ec.generate_private_key(ec.SECP256R1()).public_key()
      >>> valid_after = datetime.datetime(
      ...     2023, 1, 1, 1, tzinfo=datetime.timezone.utc
      ... ).timestamp()
      >>> valid_before = datetime.datetime(
      ...     2023, 7, 1, 1, tzinfo=datetime.timezone.utc
      ... ).timestamp()
      >>> key_id = b"a_key_id"
      >>> valid_principals = [b"eve", b"alice"]
      >>> builder = (
      ...     SSHCertificateBuilder()
      ...     .public_key(public_key)
      ...     .type(SSHCertificateType.USER)
      ...     .valid_before(valid_before)
      ...     .valid_after(valid_after)
      ...     .key_id(b"a_key_id")
      ...     .valid_principals(valid_principals)
      ...     .add_extension(b"no-touch-required", b"")
      ... )
      >>> builder.sign(signing_key).public_bytes()
      b'...'

  public_key(public_key)
    Parameters:

      public_key (`SSHCertPublicKeyTypes`) – The public key to be included in the certificate. This value is required.

  serial(serial)
    Parameters:

      serial (int) – The serial number to be included in the certificate. This is not a required value and will be set to zero if not provided. Value must be between 0 and 2:sup:64 - 1, inclusive.

  type(type)
    Parameters:

      type (`SSHCertificateType`) – The type of the certificate. There are two options, user or host.

  key_id(key_id)
    Parameters:

      key_id (bytes) – The key ID to be included in the certificate. This is not a required value.

  valid_principals(valid_principals)
    Parameters:

      valid_principals (list[bytes]) – A list of principals that the certificate is valid for. This is a required value unless `valid_for_all_principals()` has been called.

  valid_for_all_principals()

    Marks the certificate as valid for all principals. This cannot be set if principals have been added via `valid_principals()`.

  valid_after(valid_after)
    Parameters:

      valid_after (int) – The Unix timestamp (in UTC) that marks the activation time for the certificate. This is a required value.

  valid_before(valid_before)
    Parameters:

      valid_before (int) – The Unix timestamp (in UTC) that marks the expiration time for the certificate. This is a required value.

  add_critical_option(name, value)
    Parameters:

      - name (bytes) – The name of the critical option to add. No duplicates are allowed.

      - value (bytes) – The value of the critical option to add. This is commonly an empty byte string.

  add_extension(name, value)
    Parameters:

      - name (bytes) – The name of the extension to add. No duplicates are allowed.

      - value (bytes) – The value of the extension to add.

  sign(private_key)
    Parameters:

      private_key (`SSHCertPrivateKeyTypes`) – The private key that will be used to sign the certificate.

    Returns:

      The signed certificate.

    Return type:

      `SSHCertificate`

## PKCS12

PKCS12 is a binary format described in RFC 7292. It can contain certificates, keys, and more. PKCS12 files commonly have a `pfx` or `p12` file suffix.

Note

`cryptography` only supports a single private key and associated certificates when parsing PKCS12 files at this time.

cryptography.hazmat.primitives.serialization.pkcs12.PKCS12PrivateKeyTypes

  Added in version 40.0.0.

  Type alias: A union of private key types supported for PKCS12 serialization: `RSAPrivateKey` , `EllipticCurvePrivateKey` , `Ed25519PrivateKey` , `Ed448PrivateKey` or `DSAPrivateKey`.

cryptography.hazmat.primitives.serialization.pkcs12.load_key_and_certificates(data, password)

  Added in version 2.5.

  Deserialize a PKCS12 blob.

  Parameters:

    - data (bytes-like) – The binary data.

    - password (bytes-like) – The password to use to decrypt the data. `None` if the PKCS12 is not encrypted.

  Returns:

    A tuple of `(private_key, certificate, additional_certificates)`. `private_key` is a private key type or `None`, `certificate` is either the `Certificate` whose public key matches the private key in the PKCS 12 object or `None`, and `additional_certificates` is a list of all other `Certificate` instances in the PKCS12 object.

cryptography.hazmat.primitives.serialization.pkcs12.load_pkcs12(data, password)

  Added in version 36.0.0.

  Deserialize a PKCS12 blob, and return a `PKCS12KeyAndCertificates` instance.

  Parameters:

    - data (bytes-like) – The binary data.

    - password (bytes-like) – The password to use to decrypt the data. `None` if the PKCS12 is not encrypted.

  Returns:

    A `PKCS12KeyAndCertificates` instance.

cryptography.hazmat.primitives.serialization.pkcs12.serialize_key_and_certificates(name, key, cert, cas, encryption_algorithm)

  Added in version 3.0.

  Note

  With OpenSSL 3.0.0+ the defaults for encryption when serializing PKCS12 have changed and some versions of Windows and macOS will not be able to read the new format. Maximum compatibility can be achieved by using `SHA1` for MAC algorithm and `PBESv1SHA1And3KeyTripleDESCBC` for encryption algorithm as seen in the example below. However, users should avoid this unless required for compatibility.

  Warning

  PKCS12 encryption is typically not secure and should not be used as a security mechanism. Wrap a PKCS12 blob in a more secure envelope if you need to store or send it safely.

  Serialize a PKCS12 blob.

  Note

  Due to a bug in Firefox it’s not possible to load unencrypted PKCS12 blobs in Firefox.

  Parameters:

    - name (bytes) – The friendly name to use for the supplied certificate and key.

    - key (`PKCS12PrivateKeyTypes`) – The private key to include in the structure.

    - cert (`Certificate` or `None`) – The certificate associated with the private key.

    - cas (`None`, or list of `Certificate` or `PKCS12Certificate`) – An optional set of certificates to also include in the structure. If a `PKCS12Certificate` is given, its friendly name will be serialized.

    - encryption_algorithm – The encryption algorithm that should be used for the key and certificate. An instance of an object conforming to the `KeySerializationEncryption` interface. PKCS12 encryption is typically very weak and should not be used as a security boundary.

  Return bytes:

    Serialized PKCS12.

      >>> from cryptography import x509
      >>> from cryptography.hazmat.primitives.serialization import BestAvailableEncryption, load_pem_private_key, pkcs12
      >>> cert = x509.load_pem_x509_certificate(ca_cert)
      >>> key = load_pem_private_key(ca_key, None)
      >>> p12 = pkcs12.serialize_key_and_certificates(
      ...     b"friendlyname", key, cert, None, BestAvailableEncryption(b"password")
      ... )

  This example uses an `encryption_builder()` to create a PKCS12 with more compatible, but substantially less secure, encryption.

      >>> from cryptography import x509
      >>> from cryptography.hazmat.primitives import hashes
      >>> from cryptography.hazmat.primitives.serialization import PrivateFormat, load_pem_private_key, pkcs12
      >>> encryption = (
      ...     PrivateFormat.PKCS12.encryption_builder().
      ...     kdf_rounds(50000).
      ...     key_cert_algorithm(pkcs12.PBES.PBESv1SHA1And3KeyTripleDESCBC).
      ...     hmac_hash(hashes.SHA1()).build(b"my password")
      ... )
      >>> cert = x509.load_pem_x509_certificate(ca_cert)
      >>> key = load_pem_private_key(ca_key, None)
      >>> p12 = pkcs12.serialize_key_and_certificates(
      ...     b"friendlyname", key, cert, None, encryption
      ... )

class cryptography.hazmat.primitives.serialization.pkcs12.PKCS12Certificate

  Added in version 36.0.0.

  Represents additional data provided for a certificate in a PKCS12 file.

  certificate

    A `Certificate` instance.

  friendly_name
    Type:

      bytes or None

    An optional byte string containing the friendly name of the certificate.

class cryptography.hazmat.primitives.serialization.pkcs12.PKCS12KeyAndCertificates

  Added in version 36.0.0.

  A simplified representation of a PKCS12 file.

  key

    An optional private key belonging to `cert` (see `PKCS12PrivateKeyTypes`).

  cert

    An optional `PKCS12Certificate` instance belonging to the private key `key`.

  additional_certs

    A list of `PKCS12Certificate` instances.

class cryptography.hazmat.primitives.serialization.pkcs12.PBES

  Added in version 38.0.0.

  An enumeration of password-based encryption schemes used in PKCS12. These values are used with `KeySerializationEncryptionBuilder`.

  PBESv1SHA1And3KeyTripleDESCBC

    PBESv1 using SHA1 as the KDF PRF and 3-key triple DES-CBC as the cipher.

  PBESv2SHA256AndAES256CBC

    PBESv2 using SHA256 as the KDF PRF and AES256-CBC as the cipher. This is only supported on OpenSSL 3.0.0 or newer.

## PKCS7

PKCS7 is a format described in RFC 2315, among other specifications. It can contain certificates, CRLs, and much more. PKCS7 files commonly have a `p7b`, `p7m`, or `p7s` file suffix but other suffixes are also seen in the wild.

Note

`cryptography` only supports parsing certificates from PKCS7 files at this time.

cryptography.hazmat.primitives.serialization.pkcs7.PKCS7HashTypes

  Added in version 40.0.0.

  Type alias: A union of hash types supported for PKCS7 serialization: `SHA1`, `SHA224`, `SHA256`, `SHA384`, or `SHA512`.

cryptography.hazmat.primitives.serialization.pkcs7.PKCS7PrivateKeyTypes

  Added in version 40.0.0.

  Type alias: A union of private key types supported for PKCS7 serialization: `RSAPrivateKey` or `EllipticCurvePrivateKey`

cryptography.hazmat.primitives.serialization.pkcs7.load_pem_pkcs7_certificates(data)

  Added in version 3.1.

  Deserialize a PEM encoded PKCS7 blob to a list of certificates. PKCS7 can contain many other types of data, including CRLs, but this function will ignore everything except certificates.

  Parameters:

    data (bytes) – The data.

  Returns:

    A list of `Certificate`.

  Raises:

    - ValueError – If the PKCS7 data could not be loaded.

    - cryptography.exceptions.UnsupportedAlgorithm – If the PKCS7 data is of a type that is not supported.

cryptography.hazmat.primitives.serialization.pkcs7.load_der_pkcs7_certificates(data)

  Added in version 3.1.

  Deserialize a DER encoded PKCS7 blob to a list of certificates. PKCS7 can contain many other types of data, including CRLs, but this function will ignore everything except certificates.

  Parameters:

    data (bytes) – The data.

  Returns:

    A list of `Certificate`.

  Raises:

    - ValueError – If the PKCS7 data could not be loaded.

    - cryptography.exceptions.UnsupportedAlgorithm – If the PKCS7 data is of a type that is not supported.

cryptography.hazmat.primitives.serialization.pkcs7.serialize_certificates(certs, encoding)

  Added in version 37.0.0.

  Serialize a list of certificates to a PKCS7 structure.

  Parameters:

    - certs – A list of `Certificate`.

    - encoding – `PEM` or `DER`.

  Returns bytes:

    The serialized PKCS7 data.

class cryptography.hazmat.primitives.serialization.pkcs7.PKCS7SignatureBuilder

  The PKCS7 signature builder can create both basic PKCS7 signed messages as well as S/MIME messages, which are commonly used in email. S/MIME has multiple versions, but this implements a subset of RFC 2632, also known as S/MIME Version 3.

  Added in version 3.2.

      >>> from cryptography import x509
      >>> from cryptography.hazmat.primitives import hashes, serialization
      >>> from cryptography.hazmat.primitives.serialization import pkcs7
      >>> cert = x509.load_pem_x509_certificate(ca_cert)
      >>> key = serialization.load_pem_private_key(ca_key, None)
      >>> options = [pkcs7.PKCS7Options.DetachedSignature]
      >>> pkcs7.PKCS7SignatureBuilder().set_data(
      ...     b"data to sign"
      ... ).add_signer(
      ...     cert, key, hashes.SHA256()
      ... ).sign(
      ...     serialization.Encoding.SMIME, options
      ... )
      b'...'

  set_data(data)
    Parameters:

      data (bytes-like) – The data to be hashed and signed.

  add_signer(certificate, private_key, hash_algorithm, *, rsa_padding=None)
    Parameters:

      - certificate – The `Certificate`.

      - private_key – The `RSAPrivateKey` or `EllipticCurvePrivateKey` associated with the certificate provided (matches `PKCS7PrivateKeyTypes`).

      - hash_algorithm – The `HashAlgorithm` that will be used to generate the signature. This must be one of the types in `PKCS7HashTypes`.

      - rsa_padding –

        Added in version 42.0.0.

        This is a keyword-only argument. If `private_key` is an `RSAPrivateKey` then this can be set to either `PKCS1v15` or `PSS` to sign with those respective paddings. If this is `None` then RSA keys will default to `PKCS1v15` padding. All other key types must not pass a value other than `None`.

  add_certificate(certificate)

    Add an additional certificate (typically used to help build a verification chain) to the PKCS7 structure. This method may be called multiple times to add as many certificates as desired.

    Parameters:

      certificate – The `Certificate` to add.

  sign(encoding, options)
    Parameters:

      - encoding – `PEM`, `DER`, or `SMIME`.

      - options – A list of `PKCS7Options`.

    Returns bytes:

      The signed PKCS7 message.

class cryptography.hazmat.primitives.serialization.pkcs7.PKCS7EnvelopeBuilder

  The PKCS7 envelope builder can create encrypted S/MIME messages, which are commonly used in email. S/MIME has multiple versions, but this implements a subset of RFC 5751, also known as S/MIME Version 3.2.

  Added in version 43.0.0.

      >>> from cryptography import x509
      >>> from cryptography.hazmat.primitives import serialization
      >>> from cryptography.hazmat.primitives.serialization import pkcs7
      >>> cert = x509.load_pem_x509_certificate(ca_cert_rsa)
      >>> options = [pkcs7.PKCS7Options.Text]
      >>> pkcs7.PKCS7EnvelopeBuilder().set_data(
      ...     b"data to encrypt"
      ... ).add_recipient(
      ...     cert
      ... ).encrypt(
      ...     serialization.Encoding.SMIME, options
      ... )
      b'...'

  set_data(data)
    Parameters:

      data (bytes-like) – The data to be encrypted.

  add_recipient(certificate)

    Add a recipient for the message. Recipients will be able to use their private keys to decrypt the message. This method may be called multiple times to add as many recipients as desired.

    Parameters:

      certificate – A `Certificate` for an intended recipient of the encrypted message. Only certificates with public RSA keys are currently supported.

  encrypt(encoding, options)

    The message is encrypted using AES-128-CBC. The encryption key used is included in the envelope, encrypted using the recipient’s public RSA key. If multiple recipients are specified, the key is encrypted once with each recipient’s public key, and all encrypted keys are included in the envelope (one per recipient).

    Parameters:

      - encoding – `PEM`, `DER`, or `SMIME`.

      - options – A list of `PKCS7Options`. For this operation only `Text` and `Binary` are supported.

    Returns bytes:

      The enveloped PKCS7 message.

class cryptography.hazmat.primitives.serialization.pkcs7.PKCS7Options

  Added in version 3.2.

  An enumeration of options for PKCS7 signature and envelope creation.

  Text

    The text option adds `text/plain` headers to an S/MIME message when serializing to `SMIME`. This option is disallowed with `DER` serialization.

  Binary

    Signing normally converts line endings (LF to CRLF). When passing this option the data will not be converted.

  DetachedSignature

    Don’t embed the signed data within the ASN.1. When signing with `SMIME` this also results in the data being added as clear text before the PEM encoded structure.

  NoCapabilities

    PKCS7 structures contain a `MIMECapabilities` section inside the `authenticatedAttributes`. Passing this as an option removes `MIMECapabilities`.

  NoAttributes

    PKCS7 structures contain an `authenticatedAttributes` section. Passing this as an option removes that section. Note that if you pass `NoAttributes` you can’t pass `NoCapabilities` since `NoAttributes` removes `MIMECapabilities` and more.

  NoCerts

    Don’t include the signer’s certificate in the PKCS7 structure. This can reduce the size of the signature but requires that the recipient can obtain the signer’s certificate by other means (for example from a previously signed message).

## Serialization Formats

class cryptography.hazmat.primitives.serialization.PrivateFormat

  Added in version 0.8.

  An enumeration for private key formats. Used with the `private_bytes` method available on `RSAPrivateKey` , `EllipticCurvePrivateKey` , `DHPrivateKey` and `DSAPrivateKey`.

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

  Raw

    Added in version 2.5.

    A raw format used by X448 key exchange. It is a binary format and is invalid for other key types.

  OpenSSH

    Added in version 3.0.

    Custom private key format for OpenSSH, internals are based on SSH protocol and not ASN1. Requires `PEM` encoding.

    A PEM encoded OpenSSH key will look like:

        -----BEGIN OPENSSH PRIVATE KEY-----
        ...
        -----END OPENSSH PRIVATE KEY-----

  PKCS12

    Added in version 38.0.0.

    The PKCS#12 format is a binary format used to store private keys and certificates. This attribute is used in conjunction with `encryption_builder()` to allow control of the encryption algorithm and parameters.

        >>> from cryptography.hazmat.primitives import hashes
        >>> from cryptography.hazmat.primitives.serialization import PrivateFormat, pkcs12
        >>> encryption = (
        ...     PrivateFormat.PKCS12.encryption_builder().
        ...     kdf_rounds(50000).
        ...     key_cert_algorithm(pkcs12.PBES.PBESv2SHA256AndAES256CBC).
        ...     hmac_hash(hashes.SHA256()).build(b"my password")
        ... )
        >>> p12 = pkcs12.serialize_key_and_certificates(
        ...     b"friendlyname", key, None, None, encryption
        ... )

  encryption_builder()

    Added in version 38.0.0.

    Returns a builder for configuring how values are encrypted with this format. You must call this method on an element of the enumeration. For example, `PrivateFormat.OpenSSH.encryption_builder()`.

    For most use cases, `BestAvailableEncryption` is preferred.

    Returns:

      A new instance of `KeySerializationEncryptionBuilder`

        >>> from cryptography.hazmat.primitives import serialization
        >>> encryption = (
        ...     serialization.PrivateFormat.OpenSSH.encryption_builder().kdf_rounds(30).build(b"my password")
        ... )
        >>> key.private_bytes(
        ...     encoding=serialization.Encoding.PEM,
        ...     format=serialization.PrivateFormat.OpenSSH,
        ...     encryption_algorithm=encryption
        ... )
        b'-----BEGIN OPENSSH PRIVATE KEY-----\n...\n-----END OPENSSH PRIVATE KEY-----\n'

class cryptography.hazmat.primitives.serialization.PublicFormat

  Added in version 0.8.

  An enumeration for public key formats. Used with the `public_bytes` method available on `RSAPublicKey` , `EllipticCurvePublicKey` , `DHPublicKey` , and `DSAPublicKey`.

  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

    Added in version 1.4.

    The public key format used by OpenSSH (e.g. as found in `~/.ssh/id_rsa.pub` or `~/.ssh/authorized_keys`).

  Raw

    Added in version 2.5.

    A raw format used by X448 key exchange. It is a binary format and is invalid for other key types.

  CompressedPoint

    Added in version 2.5.

    A compressed elliptic curve public key as defined in ANSI X9.62 section 4.3.6 (as well as SEC 1 v2.0).

  UncompressedPoint

    Added in version 2.5.

    An uncompressed elliptic curve public key as defined in ANSI X9.62 section 4.3.6 (as well as SEC 1 v2.0).

class cryptography.hazmat.primitives.serialization.ParameterFormat

  Added in version 2.0.

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

  PKCS3

    ASN1 DH parameters sequence as defined in PKCS3.

## Serialization Encodings

class cryptography.hazmat.primitives.serialization.Encoding

  An enumeration for encoding types. Used with the `private_bytes` method available on `RSAPrivateKey` , `EllipticCurvePrivateKey` , `DHPrivateKey`, `DSAPrivateKey`, and `X448PrivateKey` as well as `public_bytes` on `RSAPublicKey`, `DHPublicKey`, `EllipticCurvePublicKey`, and `X448PublicKey`.

  PEM

    Added in version 0.8.

    For PEM format. This is a base64 format with delimiters.

  DER

    Added in version 0.9.

    For DER format. This is a binary format.

  OpenSSH

    Added in version 1.4.

    The format used by OpenSSH public keys. This is a text format.

  Raw

    Added in version 2.5.

    A raw format used by X448 key exchange. It is a binary format and is invalid for other key types.

  X962

    Added in version 2.5.

    The format used by elliptic curve point encodings. This is a binary format.

  SMIME

    Added in version 3.2.

    An output format used for PKCS7. This is a text format.

## Serialization Encryption Types

class cryptography.hazmat.primitives.serialization.KeySerializationEncryption

  Objects with this interface are usable as encryption types with methods like `private_bytes` available on `RSAPrivateKey` , `EllipticCurvePrivateKey` , `DHPrivateKey` and `DSAPrivateKey`. All other classes in this section represent the available choices for encryption and have this interface.

class cryptography.hazmat.primitives.serialization.BestAvailableEncryption(password)

  Encrypt using the best available encryption for a given key. This is a curated encryption choice and the algorithm may change over time. The encryption algorithm may vary based on which version of OpenSSL the library is compiled against.

  Parameters:

    password (bytes) – The password to use for encryption.

class cryptography.hazmat.primitives.serialization.NoEncryption

  Do not encrypt.

class cryptography.hazmat.primitives.serialization.KeySerializationEncryptionBuilder

  Added in version 38.0.0.

  A builder that can be used to configure how data is encrypted. To create one, call `PrivateFormat.encryption_builder()`. Different serialization types will support different options on this builder.

  kdf_rounds(rounds)

    Set the number of rounds the Key Derivation Function should use. The meaning of the number of rounds varies on the KDF being used.

    Parameters:

      rounds (int) – Number of rounds.

  key_cert_algorithm(algorithm)

    Set the encryption algorithm to use when encrypting the key and certificate in a PKCS12 structure.

    Parameters:

      algorithm – A value from the `PBES` enumeration.

  hmac_hash(algorithm)

    Set the hash algorithm to use within the MAC for a PKCS12 structure.

    Parameters:

      algorithm – An instance of a `HashAlgorithm`

  build(password)

    Turns the builder into an instance of `KeySerializationEncryption` with a given password.

    Parameters:

      password (bytes) – The password.

    Returns:

      A `KeySerializationEncryption` encryption object that can be passed to methods like `private_bytes` or `serialize_key_and_certificates()`.