Search documentation of public_key

# public_key (public_key v1.21.4)

Copy Markdown View Source

API module for public-key infrastructure.

Provides functions to handle public-key infrastructure, for details see public_key application.

#### Note

All records used in this Reference Manual are generated from ASN.1 specifications and are documented in the User's Guide. See Public-key Records.

Use the following include directive to get access to the records and constant macros described here and in the User's Guide:

     -include_lib("public_key/include/public_key.hrl").

## Summary

### Types: Certificate Revocation

crl_reason()

The reason that a certifcate has been revoked as define by RFC 5280.

### Types: Certificates

bad_cert_reason()

The reason that a certifcate gets rejected by the certificate path validation.

cert()

An encoded or decode certificate.

cert_id()

A certificate is identified by its serial-number and Issuer Name.

combined_cert()

A record that can be used to provide the certificate on both the DER encoded and the OTP decode format.

issuer_name()

The value of the issuer part of a certificate.

policy_node()

Certificate policy information.

public_key_info()

Information a certificates public key.

### Types: Common

asn1_type()

ASN.1 type present in the Public Key applications ASN.1 specifications.

der_encoded()

ASN.1 DER encoded entity.

digest_type()

Hash function used to create a message digest

oid()

Object identifier, a tuple of integers as generated by the `ASN.1` compiler.

### Types: Keys

custom_key_opts()

Can be provided together with a custom private key, that specifies a key fun, to provide additional options understood by the fun.

dsa_private_key()

ASN.1 defined private key format for the DSA algorithm.

dsa_public_key()

ASN.1 defined public key format for the DSA algorithm.

dss_public_key()

ASN.1 defined public key format for the DSS algorithm (part of DSA key).

ecdsa_public_key()

ASN.1 defined public key format for the ECDSA algorithm.

eddsa_private_key()

ASN.1 defined private key format for the EDDSA algorithm, possible oids: ?'id-Ed25519' | ?'id-Ed448'

eddsa_public_key()

ASN.1 defined public key format for the EDDSA algorithm, possible oids: ?'id-Ed25519' | ?'id-Ed448'

public_key()

Supported public keys

rsa_private_key()

ASN.1 defined private key format plain RSA algorithm or customization fun.

rsa_pss_private_key()

ASN.1 defined private key format the RSSASSA-PSS algorithm or customization fun.

rsa_pss_public_key()

ASN.1 defined public key format for the RSSASSA-PSS algorithm.

rsa_public_key()

ASN.1 defined public key format for plain RSA algorithm.

### Types: PEM files

pem_entry()

Possible `Ciphers` are "RC2-CBC" | "DES-CBC" | "DES-EDE3-CBC" `Salt` could be generated with `crypto:strong_rand_bytes(8)`.

pki_asn1_type()

ASN.1 type that can be found in PEM files that can be decode by the public_key application.

### Types: Test Data

cert_opt()

Options to customize generated test certificates

chain_opts()

Certificate customize options for diffrent parts of the certificate test chain.

conf_opt()

Configuration options for the generated certificate test chain.

### Types

ecdsa_private_key()

ASN.1 defined private key format for the ECDSA algorithm.

key_params()

ASN.1 defined parameters for public key algorithms.

legacy_digest_type()
ml_kem_private_key()

ML-KEM private key

ml_kem_public_key()

ML-KEM public key

mldsa_private_key()

ML-DSA private key

mldsa_public_key()

ML-DSA public key

private_key()

Supported private keys

slh_dsa_private_key()

SLH-DSA private key

slh_dsa_public_key()

SLH-DSA public key

### ASN.1 Encoding API

der_decode(Asn1Type, Der)

Decodes a public-key ASN.1 DER encoded entity.

der_encode(Asn1Type, Entity)

Encodes a public-key entity with ASN.1 DER encoding.

### Certificate API

cacerts_clear()

Clears any loaded CA certificates, returns true if any was loaded.

cacerts_get()

Returns the trusted CA certificates if any are loaded, otherwise uses `cacerts_load/0` to load them. The function fails if no `cacerts` could be loaded.

cacerts_load()

Loads the OS supplied trusted CA certificates.

cacerts_load(File)

Loads the trusted CA certificates from a file.

pkix_decode_cert(Cert, Type)

Decodes an ASN.1 DER-encoded PKIX certificate.

pkix_encode(Asn1Type, Entity, Type)

DER encodes a PKIX x509 certificate or part of such a certificate.

pkix_hash_type(HashOid)

Translates OID to Erlang digest type

pkix_is_fixed_dh_cert(Cert)

Checks if a certificate is a fixed Diffie-Hellman certificate.

pkix_is_issuer(CertorCRL, IssuerCert)

Checks if `IssuerCert` issued `Cert`.

pkix_is_self_signed(Cert)

Checks if a certificate is self-signed.

pkix_issuer_id(Cert, IssuedBy)

Returns the x509 certificate issuer id, if it can be determined.

pkix_normalize_name(Issuer)

Normalizes an issuer name so that it can be easily compared to another issuer name.

pkix_path_validation(Cert, CertChain, Options)

Performs a basic path validation according to RFC 5280.

pkix_sign_types(AlgorithmId)

Translates signature algorithm OID to Erlang digest and signature types.

pkix_subject_id(Cert)

Returns the X509 certificate subject id.

pkix_verify_hostname(Cert, ReferenceIDs)

Equivalent to `pkix_verify_hostname(Cert, ReferenceIDs, [])`.

pkix_verify_hostname(Cert, ReferenceIDs, Options)

This function checks that the Presented Identifier (e.g hostname) in a peer certificate is in agreement with at least one of the Reference Identifier that the client expects to be connected to.

pkix_verify_hostname_match_fun(Protocol)

The return value of calling this function is intended to be used in the `match_fun` option in `pkix_verify_hostname/3`.

### Certificate Revocation API

pkix_crl_issuer(CRL)

Returns the issuer of the `CRL`.

pkix_crl_verify(CRL, Cert)

Verify that `Cert` is the `CRL` signer.

pkix_crls_validate(OTPcertificate, DPandCRLs, Options)

Performs CRL validation. It is intended to be called from the verify fun of pkix_path_validation/3 .

pkix_dist_point(Cert)

Creates a distribution point for CRLs issued by the same issuer as `Cert`. Can be used as input to `pkix_crls_validate/3`

pkix_dist_points(Cert)

Extracts distribution points from the certificates extensions.

pkix_match_dist_point(CRL, DistPoint)

Checks whether the given distribution point matches the Issuing Distribution Point of the CRL, as described in RFC 5280.

pkix_ocsp_validate(Cert, IssuerCert, OcspRespDer, NonceExt, Options)

Perform OCSP response validation according to RFC 6960. Returns {'ok', Details} when OCSP response is successfully validated and {error, {bad_cert, Reason}} otherwise.

short_name_hash(Name)

Generates a short hash of an issuer name. The hash is returned as a string containing eight hexadecimal digits.

### Key API

compute_key(OthersECDHkey, MyECDHkey)

Computes shared secret.

compute_key(OthersDHkey, MyDHkey, DHparms)

Computes shared secret.

dh_gex_group(MinSize, SuggestedSize, MaxSize, Groups)

Selects a group for Diffie-Hellman key exchange with the key size in the range `MinSize...MaxSize` and as close to `SuggestedSize` as possible. If `Groups == undefined` a default set will be used, otherwise the group is selected from `Groups`.

generate_key/1

Generates a new key pair. Note that except for Diffie-Hellman the public key is included in the private key structure. See also `crypto:generate_key/2`

### Legacy RSA Encryption API

decrypt_private(CipherText, Key)

Equivalent to `decrypt_private(CipherText, Key, [])`.

decrypt_private(CipherText, Key, Options)

Public-key decryption using the private key. See also `crypto:private_decrypt/4`

decrypt_public(CipherText, Key)

Equivalent to `decrypt_public(CipherText, Key, [])`.

decrypt_public(CipherText, Key, Options)

Public-key decryption using the public key. See also `crypto:public_decrypt/4`

encrypt_private(PlainText, Key)

Equivalent to `encrypt_private(PlainText, Key, [])`.

encrypt_private(PlainText, Key, Options)

Public-key encryption using the private key.

encrypt_public(PlainText, Key)

Equivalent to `encrypt_public(PlainText, Key, [])`.

encrypt_public(PlainText, Key, Options)

Public-key encryption using the public key. See also `crypto:public_encrypt/4`.

### PEM API

pem_decode(PemBin)

Decodes PEM binary data and returns entries as ASN.1 DER encoded entities.

pem_encode(PemEntries)

Creates a PEM binary.

pem_entry_decode(PemEntry)

Equivalent to `pem_entry_decode(PemEntry, "")`.

pem_entry_decode(PemEntry, Password)

Decodes a PEM entry. `pem_decode/1` returns a list of PEM entries. Notice that if the PEM entry is of type 'SubjectPublickeyInfo', it is further decoded to an `rsa_public_key/0` or `dsa_public_key/0`.

pem_entry_encode(Asn1Type, Entity)

Equivalent to `pem_entry_encode/3`.

pem_entry_encode(Asn1Type, Entity, InfoPwd)

Creates a PEM entry that can be feed to `pem_encode/1`.

### Sign/Verify API

pkix_sign(Cert, Key)

Signs an 'OTPTBSCertificate'. Returns the corresponding DER-encoded certificate.

pkix_verify(Cert, Key)

Verifies PKIX x.509 certificate signature.

sign(Msg, DigestType, Key)

Equivalent to `sign(Msg, DigestType, Key, [])`.

sign(Msg, DigestType, Key, Options)

Creates a digital signature.

verify(Msg, DigestType, Signature, Key)

Equivalent to `verify(Msg, DigestType, Signature, Key, [])`.

verify(Msg, DigestType, Signature, Key, Options)

Verifies a digital signature.

### Test Data API

pkix_test_data(ChainConf)

Creates certificate configuration(s) consisting of certificate and its private key plus CA certificate bundle, for a client and a server, intended to facilitate automated testing of applications using X509-certificates, often through SSL/TLS. The test data can be used when you have control over both the client and the server in a test scenario.

pkix_test_root_cert(Name, Options)

Generates a root certificate that can be used in multiple calls to `pkix_test_data/1` when you want the same root certificate for several generated certificates.

## Types: Certificate Revocation

# crl_reason()

(not exported)

    -type crl_reason() ::
              unspecified | keyCompromise | cACompromise | affiliationChanged | superseded |
              cessationOfOperation | certificateHold | privilegeWithdrawn | aACompromise.

The reason that a certifcate has been revoked as define by RFC 5280.

## Types: Certificates

# bad_cert_reason()

    -type bad_cert_reason() ::
              cert_expired | invalid_issuer | invalid_signature | distinguished_name_not_permitted |
              name_not_permitted | missing_basic_constraint | invalid_key_usage | duplicate_cert_in_path |
              {key_usage_mismatch, term()} |
              {policy_requirement_not_met, term()} |
              {invalid_policy_mapping, term()} |
              {revoked, crl_reason()} |
              invalid_validity_dates | policy_tree_exceeded |
              {revocation_status_undetermined, term()} |
              atom().

The reason that a certifcate gets rejected by the certificate path validation.

# cert()

    -type cert() ::
              der_encoded() |
              #'OTPCertificate'{tbsCertificate :: term(), signatureAlgorithm :: term(), signature :: term()}.

An encoded or decode certificate.

# cert_id()

    -type cert_id() :: {SerialNr :: integer(), issuer_name()}.

A certificate is identified by its serial-number and Issuer Name.

# combined_cert()

    -type combined_cert() ::
              #cert{der :: public_key:der_encoded(),
                    otp ::
                        #'OTPCertificate'{tbsCertificate :: term(),
                                          signatureAlgorithm :: term(),
                                          signature :: term()}}.

A record that can be used to provide the certificate on both the DER encoded and the OTP decode format.

Such a construct can be useful to avoid conversions and problems that can arise due to relaxed decoding rules.

# issuer_name()

    -type issuer_name() :: {rdnSequence, [[#'AttributeTypeAndValue'{type :: term(), value :: term()}]]}.

The value of the issuer part of a certificate.

# policy_node()

    -type policy_node() ::
              #{valid_policy := oid(),
                qualifier_set :=
                    [#'UserNotice'{noticeRef :: term(), explicitText :: term()} | {uri, string()}],
                expected_policy_set := [oid()]}.

Certificate policy information.

# public_key_info()

    -type public_key_info() ::
              {oid(), rsa_public_key() | #'ECPoint'{point :: term()} | dss_public_key(), key_params()}.

Information a certificates public key.

Possible oids: ?'rsaEncryption' | ?'id-RSASSA-PSS' | ?'id-ecPublicKey' | ?'id-Ed25519' | ?'id-Ed448' | ?'id-dsa'

## Types: Common

# asn1_type()

    -type asn1_type() :: atom().

ASN.1 type present in the Public Key applications ASN.1 specifications.

# der_encoded()

    -type der_encoded() :: binary().

ASN.1 DER encoded entity.

# digest_type()

    -type digest_type() :: crypto:sha2() | crypto:sha1() | legacy_digest_type() | none.

Hash function used to create a message digest

# oid()

    -type oid() :: tuple().

Object identifier, a tuple of integers as generated by the `ASN.1` compiler.

## Types: Keys

# custom_key_opts()

    -type custom_key_opts() :: [term()].

Can be provided together with a custom private key, that specifies a key fun, to provide additional options understood by the fun.

# dsa_private_key()

    -type dsa_private_key() ::
              #'DSAPrivateKey'{version :: term(),
                               p :: term(),
                               q :: term(),
                               g :: term(),
                               y :: term(),
                               x :: term()}.

ASN.1 defined private key format for the DSA algorithm.

# dsa_public_key()

    -type dsa_public_key() :: {dss_public_key(), #'Dss-Parms'{p :: term(), q :: term(), g :: term()}}.

ASN.1 defined public key format for the DSA algorithm.

# dss_public_key()

(not exported)

    -type dss_public_key() :: pos_integer().

ASN.1 defined public key format for the DSS algorithm (part of DSA key).

# ecdsa_public_key()

    -type ecdsa_public_key() ::
              {#'ECPoint'{point :: term()},
               {namedCurve, oid()} |
               #'ECParameters'{version :: term(),
                               fieldID :: term(),
                               curve :: term(),
                               base :: term(),
                               order :: term(),
                               cofactor :: term()}}.

ASN.1 defined public key format for the ECDSA algorithm.

# eddsa_private_key()

    -type eddsa_private_key() ::
              #'ECPrivateKey'{parameters :: {namedCurve, oid()},
                              version :: term(),
                              privateKey :: term(),
                              publicKey :: term(),
                              attributes :: term()}.

ASN.1 defined private key format for the EDDSA algorithm, possible oids: ?'id-Ed25519' | ?'id-Ed448'

# eddsa_public_key()

    -type eddsa_public_key() :: {#'ECPoint'{point :: term()}, {namedCurve, oid()}}.

ASN.1 defined public key format for the EDDSA algorithm, possible oids: ?'id-Ed25519' | ?'id-Ed448'

# public_key()

    -type public_key() ::
              rsa_public_key() |
              rsa_pss_public_key() |
              dsa_public_key() |
              ecdsa_public_key() |
              eddsa_public_key() |
              mldsa_public_key() |
              ml_kem_public_key() |
              slh_dsa_public_key().

Supported public keys

# rsa_private_key()

    -type rsa_private_key() ::
              #'RSAPrivateKey'{version :: term(),
                               modulus :: term(),
                               publicExponent :: term(),
                               privateExponent :: term(),
                               prime1 :: term(),
                               prime2 :: term(),
                               exponent1 :: term(),
                               exponent2 :: term(),
                               coefficient :: term(),
                               otherPrimeInfos :: term()} |
              #{algorithm := rsa, encrypt_fun => fun()}.

ASN.1 defined private key format plain RSA algorithm or customization fun.

# rsa_pss_private_key()

    -type rsa_pss_private_key() ::
              {#'RSAPrivateKey'{version :: term(),
                                modulus :: term(),
                                publicExponent :: term(),
                                privateExponent :: term(),
                                prime1 :: term(),
                                prime2 :: term(),
                                exponent1 :: term(),
                                exponent2 :: term(),
                                coefficient :: term(),
                                otherPrimeInfos :: term()},
               #'RSASSA-PSS-params'{hashAlgorithm :: term(),
                                    maskGenAlgorithm :: term(),
                                    saltLength :: term(),
                                    trailerField :: term()}}.

ASN.1 defined private key format the RSSASSA-PSS algorithm or customization fun.

# rsa_pss_public_key()

    -type rsa_pss_public_key() ::
              {rsa_public_key(),
               #'RSASSA-PSS-params'{hashAlgorithm :: term(),
                                    maskGenAlgorithm :: term(),
                                    saltLength :: term(),
                                    trailerField :: term()}}.

ASN.1 defined public key format for the RSSASSA-PSS algorithm.

# rsa_public_key()

    -type rsa_public_key() :: #'RSAPublicKey'{modulus :: term(), publicExponent :: term()}.

ASN.1 defined public key format for plain RSA algorithm.

## Types: PEM files

# pem_entry()

    -type pem_entry() ::
              {pki_asn1_type(),
               DerOrDerEncrypted :: binary(),
               not_encrypted |
               {Cipher :: iodata(),
                Salt ::
                    binary() |
                    {#'PBEParameter'{salt :: term(), iterationCount :: term()}, digest_type()} |
                    #'PBES2-params'{keyDerivationFunc :: term(), encryptionScheme :: term()}}}.

Possible `Ciphers` are "RC2-CBC" | "DES-CBC" | "DES-EDE3-CBC" `Salt` could be generated with `crypto:strong_rand_bytes(8)`.

# pki_asn1_type()

    -type pki_asn1_type() ::
              'Certificate' | 'RSAPrivateKey' | 'RSAPublicKey' | 'SubjectPublicKeyInfo' | 'DSAPrivateKey' |
              'DHParameter' | 'PrivateKeyInfo' | 'CertificationRequest' | 'ContentInfo' |
              'CertificateList' | 'ECPrivateKey' | 'OneAsymmetricKey' | 'EcpkParameters'.

ASN.1 type that can be found in PEM files that can be decode by the public_key application.

## Types: Test Data

# cert_opt()

    -type cert_opt() ::
              {digest, digest_type()} |
              {key,
               {namedCurve, oid()} |
               #'ECParameters'{version :: term(),
                               fieldID :: term(),
                               curve :: term(),
                               base :: term(),
                               order :: term(),
                               cofactor :: term()} |
               {rsa, Size :: pos_integer(), Prime :: pos_integer()} |
               private_key()} |
              {validity, {From :: erlang:timestamp(), To :: erlang:timestamp()}} |
              {extensions, [#'Extension'{extnID :: term(), critical :: term(), extnValue :: term()}]}.

Options to customize generated test certificates

# chain_opts()

    -type chain_opts() :: #{root := [cert_opt()], intermediates => [[cert_opt()]], peer := [cert_opt()]}.

Certificate customize options for diffrent parts of the certificate test chain.

# conf_opt()

    -type conf_opt() ::
              {cert, der_encoded()} |
              {key, private_key() | {both, public_key(), private_key()}} |
              {cacerts, [der_encoded()]}.

Configuration options for the generated certificate test chain.

## Types

# ecdsa_private_key()

    -type ecdsa_private_key() ::
              #'ECPrivateKey'{version :: term(),
                              privateKey :: term(),
                              parameters :: term(),
                              publicKey :: term(),
                              attributes :: term()}.

ASN.1 defined private key format for the ECDSA algorithm.

# key_params()

    -type key_params() ::
              'NULL' |
              #'RSASSA-PSS-params'{hashAlgorithm :: term(),
                                   maskGenAlgorithm :: term(),
                                   saltLength :: term(),
                                   trailerField :: term()} |
              {namedCurve, oid()} |
              #'ECParameters'{version :: term(),
                              fieldID :: term(),
                              curve :: term(),
                              base :: term(),
                              order :: term(),
                              cofactor :: term()} |
              #'Dss-Parms'{p :: term(), q :: term(), g :: term()}.

ASN.1 defined parameters for public key algorithms.

# legacy_digest_type()

(not exported)

    -type legacy_digest_type() :: md5 | md2.

# ml_kem_private_key()

(not exported)

    -type ml_kem_private_key() ::
              #'ML-KEMPrivateKey'{algorithm :: crypto:kem(), seed :: binary(), expandedkey :: binary()}.

ML-KEM private key

# ml_kem_public_key()

(not exported)

    -type ml_kem_public_key() :: #'ML-KEMPublicKey'{algorithm :: crypto:kem(), key :: binary()}.

ML-KEM public key

# mldsa_private_key()

    -type mldsa_private_key() ::
              #'ML-DSAPrivateKey'{algorithm :: crypto:mldsa(), seed :: binary(), expandedkey :: binary()}.

ML-DSA private key

# mldsa_public_key()

    -type mldsa_public_key() :: #'ML-DSAPublicKey'{algorithm :: crypto:mldsa(), key :: binary()}.

ML-DSA public key

# private_key()

    -type private_key() ::
              rsa_private_key() |
              rsa_pss_private_key() |
              dsa_private_key() |
              ecdsa_private_key() |
              eddsa_private_key() |
              mldsa_private_key() |
              ml_kem_private_key() |
              slh_dsa_private_key() |
              #{algorithm := slh_dsa | mldsa | eddsa | rsa_pss_pss | ecdsa | rsa | dsa, sign_fun => fun()}.

Supported private keys

# slh_dsa_private_key()

    -type slh_dsa_private_key() :: #'SLH-DSAPrivateKey'{algorithm :: crypto:slh_dsa(), key :: binary()}.

SLH-DSA private key

# slh_dsa_public_key()

    -type slh_dsa_public_key() :: #'SLH-DSAPublicKey'{algorithm :: crypto:slh_dsa(), key :: binary()}.

SLH-DSA public key

## ASN.1 Encoding API

# der_decode(Asn1Type, Der)

(since OTP R14B)

    -spec der_decode(Asn1Type, Der) -> Entity
                        when Asn1Type :: asn1_type(), Der :: der_encoded(), Entity :: term().

Decodes a public-key ASN.1 DER encoded entity.

# der_encode(Asn1Type, Entity)

(since OTP R14B)

    -spec der_encode(Asn1Type, Entity) -> Der
                        when Asn1Type :: asn1_type(), Entity :: term(), Der :: binary().

Encodes a public-key entity with ASN.1 DER encoding.

## Certificate API

# cacerts_clear()

(since OTP 25.0)

    -spec cacerts_clear() -> boolean().

Clears any loaded CA certificates, returns true if any was loaded.

# cacerts_get()

(since OTP 25.0)

    -spec cacerts_get() -> [combined_cert()].

Returns the trusted CA certificates if any are loaded, otherwise uses `cacerts_load/0` to load them. The function fails if no `cacerts` could be loaded.

# cacerts_load()

(since OTP 25.0)

    -spec cacerts_load() -> ok | {error, Reason :: term()}.

Loads the OS supplied trusted CA certificates.

This can be overridden by setting the `cacerts_path` environment key of the `public_key` application with the location of an alternative certificate. You can set it via the command line as:

    erl -public_key cacerts_path '"/path/to/certs.pem"'

Use it with care. It is your responsibility to ensure that the certificates found in this alternative path can be trusted by the running system.

# cacerts_load(File)

(since OTP 25.0)

    -spec cacerts_load(File :: file:filename_all()) -> ok | {error, Reason :: term()}.

Loads the trusted CA certificates from a file.

# pkix_decode_cert(Cert, Type)

    -spec pkix_decode_cert(Cert, Type) ->
                              #'Certificate'{toBeSigned :: term(),
                                             algorithmIdentifier :: term(),
                                             signature :: term()} |
                              #'OTPCertificate'{tbsCertificate :: term(),
                                                signatureAlgorithm :: term(),
                                                signature :: term()}
                              when Cert :: der_encoded(), Type :: plain | otp | relaxed.

Decodes an ASN.1 DER-encoded PKIX certificate.

Option `otp` uses the customized ASN.1 specification OTP-PKIX.asn1 for decoding and also recursively decode most of the standard parts.

Option `relaxed` is similar to option `otp` but also allows for empty RDNs in issuer and subject.

# pkix_encode(Asn1Type, Entity, Type)

(since OTP R14B)

    -spec pkix_encode(Asn1Type, Entity, Type) -> Der
                         when
                             Asn1Type :: asn1_type(),
                             Entity :: term(),
                             Type :: otp | plain,
                             Der :: der_encoded().

DER encodes a PKIX x509 certificate or part of such a certificate.

This function must be used for encoding certificates or parts of certificates that are decoded/created in the `otp` format, whereas for the plain format this function directly calls `der_encode/2`.

#### Note

Subtle ASN-1 encoding errors in certificates may be worked around when decoding, this may have the affect that the encoding a certificate back to DER may generate different bytes then the supplied original.

# pkix_hash_type(HashOid)

(since OTP 23.0)

    -spec pkix_hash_type(HashOid :: oid()) -> DigestType :: digest_type().

Translates OID to Erlang digest type

# pkix_is_fixed_dh_cert(Cert)

(since OTP R14B)

    -spec pkix_is_fixed_dh_cert(Cert) -> boolean() when Cert :: cert().

Checks if a certificate is a fixed Diffie-Hellman certificate.

# pkix_is_issuer(CertorCRL, IssuerCert)

(since OTP R14B)

    -spec pkix_is_issuer(CertorCRL, IssuerCert) -> boolean()
                            when
                                CertorCRL ::
                                    cert() |
                                    #'CertificateList'{toBeSigned :: term(),
                                                       algorithmIdentifier :: term(),
                                                       signature :: term()},
                                IssuerCert :: cert().

Checks if `IssuerCert` issued `Cert`.

# pkix_is_self_signed(Cert)

(since OTP R14B)

    -spec pkix_is_self_signed(Cert) -> boolean() when Cert :: cert().

Checks if a certificate is self-signed.

# pkix_issuer_id(Cert, IssuedBy)

(since OTP R14B)

    -spec pkix_issuer_id(Cert, IssuedBy) -> {ok, ID :: cert_id()} | {error, Reason}
                            when Cert :: cert(), IssuedBy :: self | other, Reason :: term().

Returns the x509 certificate issuer id, if it can be determined.

# pkix_normalize_name(Issuer)

(since OTP R14B)

    -spec pkix_normalize_name(Issuer) -> Normalized
                                 when Issuer :: issuer_name() | der_encoded(), Normalized :: issuer_name().

Normalizes an issuer name so that it can be easily compared to another issuer name.

# pkix_path_validation(Cert, CertChain, Options)

(since OTP R16B)

    -spec pkix_path_validation(Cert, CertChain, Options) ->
                                  {ok, {PublicKeyInfo, ConstrainedPolicyNodes}} |
                                  {error, {bad_cert, Reason :: bad_cert_reason()}}
                                  when
                                      Cert :: cert() | combined_cert() | atom(),
                                      CertChain :: [cert() | combined_cert()],
                                      Options ::
                                          [{max_path_length, integer()} | {verify_fun, {fun(), term()}}],
                                      PublicKeyInfo :: public_key_info(),
                                      ConstrainedPolicyNodes :: [policy_node()].

Performs a basic path validation according to RFC 5280.

However, CRL validation is done separately by pkix_crls_validate/3 and is to be called from the supplied `verify_fun`. The policy tree check was added in OTP-26.2 and if the certificates include policies the constrained policy set with potential qualifiers will be returned, these values are derived from the policy tree created as part of the path validation algorithm. The constrained set can be constrained only by the Certificate Authorities or also by the user when the option `policy_set` is provided to this function. The qualifiers convey information about the valid policy and is intended as information to end users.

Available options:

- {verify_fun, {fun(), UserState::term()} - The fun must be defined as:

      fun(OtpCert :: #'OTPCertificate'{},
          Event :: {bad_cert, Reason :: bad_cert_reason() | {revoked, atom()}} |
                   {extension, #'Extension'{}},
          UserState :: term()) ->
        {valid, UserState :: term()} |
        {valid_peer, UserState :: term()} |
        {fail, Reason :: term()} |
        {unknown, UserState :: term()}.

  or as:

      fun(OtpCert :: #'OTPCertificate'{},
          DerCert :: der_encoded(),
          Event :: {bad_cert, Reason :: bad_cert_reason() | {revoked, atom()}} |
                   {extension, #'Extension'{}},
          UserState :: term()) ->
        {valid, UserState :: term()} |
        {valid_peer, UserState :: term()} |
        {fail, Reason :: term()} |
        {unknown, UserState :: term()}.

  The verify callback can have 3 or 4 arguments in case the DER encoded version is needed by the callback.

  If the verify callback fun returns `{fail, Reason}`, the verification process is immediately stopped. If the verify callback fun returns `{valid, UserState}`, the verification process is continued. This can be used to accept specific path validation errors, such as `selfsigned_peer`, as well as verifying application-specific extensions. If called with an extension unknown to the user application, the return value `{unknown, UserState}` is to be used.

  > #### Note

  > If you need the DER encoded version of the certificate and have the OTP decoded version encoding it back can fail to give the correct result, due to work arounds for common misbehaving encoders. So it is recommended to call `pkix_path_validation` with `Cert` and `CertChain` arguments as `der_encoded() | #cert{}` and `[der_encoded() | #cert{}]`. Also note that the path validation itself needs both the encoded and the decoded version of the certificate.

  #### Warning

  Note that user defined custom `verify_fun` may alter original path validation error (e.g `selfsigned_peer`). Use with caution.

- {max_path_length, integer()} - The `max_path_length` is the maximum number of non-self-issued intermediate certificates that can follow the peer certificate in a valid certification path. So, if `max_path_length` is 0, the PEER must be signed by the trusted ROOT-CA directly, if it is 1, the path can be PEER, CA, ROOT-CA, if it is 2, the path can be PEER, CA, CA, ROOT-CA, and so on.

- {policy_set, [oid()]}(Since OTP 26.2)
  The set of policies that will be accepted, defaults to the special value `[?anyPolicy]` that will accept all policies.

- {explicit_policy, boolean()}(Since OTP 26.2)
  Explicitly require that each certificate in the path must include at least one of the certificate policies in the `policy_set`.

- {inhibit_policy_mapping, boolean()}(Since OTP 26.2)
  Prevent policies to be mapped to other policies.

- {inhibit_any_policy, boolean()}(Since OTP 26.2)
  Prevent the special policy `?anyPolicy` from being accepted.

Explanations of reasons for a bad certificate:

- cert_expired - Certificate is no longer valid as its expiration date has passed.

- invalid_issuer - Certificate issuer name does not match the name of the issuer certificate in the chain.

- invalid_signature - Certificate was not signed by its issuer certificate in the chain.

- distinguished_name_not_permitted - Subject Name does not adhere to name constraints which is mandatory in RFC 5280.

- name_not_permitted - Subject Alternative Name does not adhere to name constraints, which is optional in RFC 5280.

- missing_basic_constraint - Certificate, required to have the basic constraints extension, does not have a basic constraints extension.

- invalid_key_usage - Certificate key is used in an invalid way according to the key-usage extension.

- {revoked, crl_reason()} - Certificate has been revoked.

- invalid_validity_dates - The validity section of the X.509 certificate(s) contains invalid date formats not matching the RFC.

- policy_tree_exceeded - The certificate chain's policy tree exceeded the maximum allowed node count. This indicates a malformed or malicious chain with exponentially expanding policy mappings. This error cannot be overridden by the `verify_fun`.

- atom() - Application-specific error reason that is to be checked by the `verify_fun`.

# pkix_sign_types(AlgorithmId)

(since OTP R16B01)

    -spec pkix_sign_types(AlgorithmId) -> {DigestType, SignatureType}
                             when
                                 AlgorithmId :: oid(),
                                 DigestType :: digest_type(),
                                 SignatureType ::
                                     rsa | dsa | ecdsa | eddsa | crypto:mldsa() | crypto:slh_dsa().

Translates signature algorithm OID to Erlang digest and signature types.

The `AlgorithmId` is the signature OID from a certificate or a certificate revocation list.

# pkix_subject_id(Cert)

(since OTP 23.1)

    -spec pkix_subject_id(Cert) -> ID when Cert :: cert(), ID :: cert_id().

Returns the X509 certificate subject id.

# pkix_verify_hostname(Cert, ReferenceIDs)

(since OTP 19.3)

    -spec pkix_verify_hostname(Cert, ReferenceIDs) -> boolean()
                                  when
                                      Cert :: cert(),
                                      ReferenceIDs ::
                                          [{uri_id | dns_id | ip | srv_id | atom() | oid(), string()} |
                                           {ip, inet:ip_address() | string()}].

Equivalent to `pkix_verify_hostname(Cert, ReferenceIDs, [])`.

# pkix_verify_hostname(Cert, ReferenceIDs, Options)

(since OTP 19.3)

    -spec pkix_verify_hostname(Cert, ReferenceIDs, Options) -> boolean()
                                  when
                                      Cert :: cert(),
                                      ReferenceIDs ::
                                          [{uri_id | dns_id | ip | srv_id | atom() | oid(), string()} |
                                           {ip, inet:ip_address() | string()}],
                                      Options :: [{match_fun | fail_callback | fqdn_fun, fun()}].

This function checks that the Presented Identifier (e.g hostname) in a peer certificate is in agreement with at least one of the Reference Identifier that the client expects to be connected to.

The function is intended to be added as an extra client check of the peer certificate when performing public_key:pkix_path_validation/3

See RFC 6125 for detailed information about hostname verification. The User's Guide and code examples describes this function more detailed.

The option funs are described here:

- `match_fun`

      fun(ReferenceId::ReferenceId() | FQDN::string(),
          PresentedId::{dNSName,string()} | {uniformResourceIdentifier,string() |
                       {iPAddress,list(byte())} | {OtherId::atom()|oid(),term()}})

  This function replaces the default host name matching rules. The fun should return a boolean to tell if the Reference ID and Presented ID matches or not. The match fun can also return a third value, value, the atom `default`, if the default matching rules shall apply. This makes it possible to augment the tests with a special case:

      fun(....) -> true;   % My special case
         (_, _) -> default % all others falls back to the inherit tests
      end

  See `pkix_verify_hostname_match_fun/1` for a function that takes a protocol name as argument and returns a `fun/2` suitable for this option and Re-defining the match operation in the User's Guide for an example.

  #### Note

  Reference Id values given as binaries will be converted to strings, and ip references may be given in string format that is "10.0.1.1" or "1234::5678:9012" as well as on the format `inet:ip_address/0`

- `fail_callback` - If a matching fails, there could be circumstances when the certificate should be accepted anyway. Think for example of a web browser where you choose to accept an outdated certificate. This option enables implementation of such an exception but for hostnames. This `fun/1` is called when no `ReferenceID` matches. The return value of the fun (a `boolean/0`) decides the outcome. If `true` the the certificate is accepted otherwise it is rejected. See "Pinning" a Certificate in the User's Guide.

- `fqdn_fun` - This option augments the host name extraction from URIs and other Reference IDs. It could for example be a very special URI that is not standardised. The fun takes a Reference ID as argument and returns one of:

  - the hostname
  - the atom `default`: the default host name extract function will be used
  - the atom `undefined`: a host name could not be extracted. The pkix_verify_hostname/3 will return `false`.

  For an example, see Hostname extraction in the User's Guide.

# pkix_verify_hostname_match_fun(Protocol)

(since OTP 21.0)

    -spec pkix_verify_hostname_match_fun(Protocol) -> Result when Protocol :: https, Result :: fun().

The return value of calling this function is intended to be used in the `match_fun` option in `pkix_verify_hostname/3`.

The returned fun augments the verify hostname matching according to the specific rules for the protocol in the argument.

#### Note

Currently supported https fun will allow wildcard certificate matching as specified by the HTTP standard. Note that for instance LDAP have a different set of wildcard matching rules. If you do not want to allow wildcard certificates (recommended from a security perspective) or otherwise customize the hostname match the default match function used by ssl application will be sufficient.

## Certificate Revocation API

# pkix_crl_issuer(CRL)

(since OTP 17.5)

    -spec pkix_crl_issuer(CRL) -> Issuer
                             when
                                 CRL ::
                                     der_encoded() |
                                     #'CertificateList'{toBeSigned :: term(),
                                                        algorithmIdentifier :: term(),
                                                        signature :: term()},
                                 Issuer :: issuer_name().

Returns the issuer of the `CRL`.

# pkix_crl_verify(CRL, Cert)

(since OTP 17.5)

    -spec pkix_crl_verify(CRL, Cert) -> boolean()
                             when
                                 CRL ::
                                     der_encoded() |
                                     #'CertificateList'{toBeSigned :: term(),
                                                        algorithmIdentifier :: term(),
                                                        signature :: term()},
                                 Cert :: cert().

Verify that `Cert` is the `CRL` signer.

# pkix_crls_validate(OTPcertificate, DPandCRLs, Options)

(since OTP R16B)

    -spec pkix_crls_validate(OTPcertificate, DPandCRLs, Options) -> CRLstatus
                                when
                                    OTPcertificate ::
                                        #'OTPCertificate'{tbsCertificate :: term(),
                                                          signatureAlgorithm :: term(),
                                                          signature :: term()},
                                    DPandCRLs :: [DPandCRL],
                                    DPandCRL :: {DP, {DerCRL, CRL}},
                                    DP ::
                                        #'DistributionPoint'{distributionPoint :: term(),
                                                             reasons :: term(),
                                                             cRLIssuer :: term()},
                                    DerCRL :: der_encoded(),
                                    CRL ::
                                        #'CertificateList'{toBeSigned :: term(),
                                                           algorithmIdentifier :: term(),
                                                           signature :: term()},
                                    Options :: [{atom(), term()}],
                                    CRLstatus :: valid | {bad_cert, BadCertReason},
                                    BadCertReason ::
                                        revocation_status_undetermined |
                                        {revocation_status_undetermined, Reason :: term()} |
                                        {revoked, crl_reason()}.

Performs CRL validation. It is intended to be called from the verify fun of pkix_path_validation/3 .

Available options:

- {update_crl, fun()} - The fun has the following type specification:

       fun(#'DistributionPoint'{}, #'CertificateList'{}) ->
              #'CertificateList'{}

  The fun uses the information in the distribution point to access the latest possible version of the CRL. If this fun is not specified, Public Key uses the default implementation:

       fun(_DP, CRL) -> CRL end

- {issuer_fun, {fun(), UserState::term()}} - The fun has the following type specification:

      fun(#'DistributionPoint'{}, #'CertificateList'{},
          {rdnSequence,[#'AttributeTypeAndValue'{}]}, UserState::term()) ->
        {ok, #'OTPCertificate'{}, [der_encoded]}

  The fun returns the root certificate and certificate chain that has signed the CRL.

       fun(DP, CRL, Issuer, UserState) -> {ok, RootCert, CertChain}

- {undetermined_details, boolean()} - Defaults to false. When revocation status cannot be determined, and this option is set to true, details of why no CRLs where accepted are included in the return value.

# pkix_dist_point(Cert)

(since OTP 17.5)

    -spec pkix_dist_point(Cert) -> DistPoint
                             when
                                 Cert :: cert(),
                                 DistPoint ::
                                     #'DistributionPoint'{distributionPoint :: term(),
                                                          reasons :: term(),
                                                          cRLIssuer :: term()}.

Creates a distribution point for CRLs issued by the same issuer as `Cert`. Can be used as input to `pkix_crls_validate/3`

# pkix_dist_points(Cert)

(since OTP 17.5)

    -spec pkix_dist_points(Cert) -> DistPoints
                              when
                                  Cert :: cert(),
                                  DistPoints ::
                                      [#'DistributionPoint'{distributionPoint :: term(),
                                                            reasons :: term(),
                                                            cRLIssuer :: term()}].

Extracts distribution points from the certificates extensions.

# pkix_match_dist_point(CRL, DistPoint)

(since OTP 19.0)

    -spec pkix_match_dist_point(CRL, DistPoint) -> boolean()
                                   when
                                       CRL ::
                                           der_encoded() |
                                           #'CertificateList'{toBeSigned :: term(),
                                                              algorithmIdentifier :: term(),
                                                              signature :: term()},
                                       DistPoint ::
                                           #'DistributionPoint'{distributionPoint :: term(),
                                                                reasons :: term(),
                                                                cRLIssuer :: term()}.

Checks whether the given distribution point matches the Issuing Distribution Point of the CRL, as described in RFC 5280.

If the CRL doesn't have an Issuing Distribution Point extension, the distribution point always matches.

# pkix_ocsp_validate(Cert, IssuerCert, OcspRespDer, NonceExt, Options)

(since OTP 27.0)

    -spec pkix_ocsp_validate(Cert, IssuerCert, OcspRespDer, NonceExt, Options) ->
                                {ok, Details} | {error, {bad_cert, Reason}}
                                when
                                    Cert :: cert(),
                                    IssuerCert :: cert(),
                                    OcspRespDer :: der_encoded(),
                                    NonceExt :: undefined | binary(),
                                    Options ::
                                        [{is_trusted_responder_fun, fun((combined_cert()) -> boolean)}],
                                    Details :: list(),
                                    Reason :: bad_cert_reason().

Perform OCSP response validation according to RFC 6960. Returns {'ok', Details} when OCSP response is successfully validated and {error, {bad_cert, Reason}} otherwise.

Available options:

- {is_trusted_responder_fun, fun()} - The fun has the following type specification:

       fun(#cert{}) ->
          boolean()

  The fun returns the `true` if certificate in the argument is trusted. If this fun is not specified, Public Key uses the default implementation:

       fun(_) -> false end

#### Note

OCSP response can be provided without a nonce value - even if it was requested by the client. In such cases {missing, ocsp_nonce} will be returned in Details list.

# short_name_hash(Name)

(since OTP 19.0)

    -spec short_name_hash(Name) -> string() when Name :: issuer_name().

Generates a short hash of an issuer name. The hash is returned as a string containing eight hexadecimal digits.

The return value of this function is the same as the result of the commands `openssl crl -hash` and `openssl x509 -issuer_hash`, when passed the issuer name of a CRL or a certificate, respectively. This hash is used by the `c_rehash` tool to maintain a directory of symlinks to CRL files, in order to facilitate looking up a CRL by its issuer name.

## Key API

# compute_key(OthersECDHkey, MyECDHkey)

(since OTP R16B01)

    -spec compute_key(OthersECDHkey, MyECDHkey) -> SharedSecret
                         when
                             OthersECDHkey :: #'ECPoint'{point :: term()},
                             MyECDHkey ::
                                 #'ECPrivateKey'{version :: term(),
                                                 privateKey :: term(),
                                                 parameters :: term(),
                                                 publicKey :: term(),
                                                 attributes :: term()},
                             SharedSecret :: binary().

Computes shared secret.

# compute_key(OthersDHkey, MyDHkey, DHparms)

(since OTP R16B01)

    -spec compute_key(OthersDHkey, MyDHkey, DHparms) -> SharedSecret
                         when
                             OthersDHkey :: crypto:dh_public(),
                             MyDHkey :: crypto:dh_private(),
                             DHparms ::
                                 #'DHParameter'{prime :: term(),
                                                base :: term(),
                                                privateValueLength :: term()},
                             SharedSecret :: binary().

Computes shared secret.

# dh_gex_group(MinSize, SuggestedSize, MaxSize, Groups)

(since OTP 18.2)

    -spec dh_gex_group(MinSize, SuggestedSize, MaxSize, Groups) -> {ok, {Size, Group}} | {error, term()}
                          when
                              MinSize :: pos_integer(),
                              SuggestedSize :: pos_integer(),
                              MaxSize :: pos_integer(),
                              Groups :: undefined | [{Size, [Group]}],
                              Size :: pos_integer(),
                              Group :: {G, P},
                              G :: pos_integer(),
                              P :: pos_integer().

Selects a group for Diffie-Hellman key exchange with the key size in the range `MinSize...MaxSize` and as close to `SuggestedSize` as possible. If `Groups == undefined` a default set will be used, otherwise the group is selected from `Groups`.

First a size, as close as possible to SuggestedSize, is selected. Then one group with that key size is randomly selected from the specified set of groups. If no size within the limits of `MinSize` and `MaxSize` is available, `{error,no_group_found}` is returned.

The default set of groups is listed in `lib/public_key/priv/moduli`. This file may be regenerated like this:

    	$> cd $ERL_TOP/lib/public_key/priv/
    	$> generate
             ---- wait until all background jobs has finished. It may take several days !
    	$> cat moduli-* > moduli
    	$> cd ..; make

# generate_key/1

(since OTP R16B01)

    -spec generate_key(DHparams | ECparams | RSAparams | MLDSA | SLHDSA) ->
                          DHkeys | ECkey | RSAkey | MLDSAKeys | SLHDSAKeys
                          when
                              DHparams ::
                                  #'DHParameter'{prime :: term(),
                                                 base :: term(),
                                                 privateValueLength :: term()},
                              DHkeys :: {PublicDH :: binary(), PrivateDH :: binary()},
                              ECparams ::
                                  {namedCurve, oid() | atom()} |
                                  #'ECParameters'{version :: term(),
                                                  fieldID :: term(),
                                                  curve :: term(),
                                                  base :: term(),
                                                  order :: term(),
                                                  cofactor :: term()},
                              ECkey ::
                                  #'ECPrivateKey'{version :: term(),
                                                  privateKey :: term(),
                                                  parameters :: term(),
                                                  publicKey :: term(),
                                                  attributes :: term()},
                              RSAparams :: {rsa, Size, PubExp},
                              Size :: pos_integer(),
                              PubExp :: pos_integer(),
                              RSAkey ::
                                  #'RSAPrivateKey'{version :: term(),
                                                   modulus :: term(),
                                                   publicExponent :: term(),
                                                   privateExponent :: term(),
                                                   prime1 :: term(),
                                                   prime2 :: term(),
                                                   exponent1 :: term(),
                                                   exponent2 :: term(),
                                                   coefficient :: term(),
                                                   otherPrimeInfos :: term()},
                              MLDSA :: crypto:mldsa(),
                              MLDSAKeys ::
                                  {#'ML-DSAPublicKey'{algorithm :: crypto:mldsa(), key :: binary()},
                                   #'ML-DSAPrivateKey'{algorithm :: crypto:mldsa(),
                                                       seed :: binary(),
                                                       expandedkey :: binary()}},
                              SLHDSA :: crypto:slh_dsa(),
                              SLHDSAKeys ::
                                  {#'SLH-DSAPublicKey'{algorithm :: crypto:slh_dsa(), key :: binary()},
                                   #'SLH-DSAPrivateKey'{algorithm :: crypto:slh_dsa(), key :: binary()}}.

Generates a new key pair. Note that except for Diffie-Hellman the public key is included in the private key structure. See also `crypto:generate_key/2`

## Legacy RSA Encryption API

# decrypt_private(CipherText, Key)

(since OTP R14B)

    -spec decrypt_private(CipherText, Key) -> PlainText
                             when CipherText :: binary(), Key :: rsa_private_key(), PlainText :: binary().

Equivalent to `decrypt_private(CipherText, Key, [])`.

# decrypt_private(CipherText, Key, Options)

(since OTP R14B)

    -spec decrypt_private(CipherText, Key, Options) -> PlainText
                             when
                                 CipherText :: binary(),
                                 Key :: rsa_private_key(),
                                 Options :: crypto:pk_encrypt_decrypt_opts(),
                                 PlainText :: binary().

Public-key decryption using the private key. See also `crypto:private_decrypt/4`

#### Warning

This is a legacy function, for security reasons do not use with rsa_pkcs1_padding.

# decrypt_public(CipherText, Key)

(since OTP R14B)

    -spec decrypt_public(CipherText, Key) -> PlainText
                            when CipherText :: binary(), Key :: rsa_public_key(), PlainText :: binary().

Equivalent to `decrypt_public(CipherText, Key, [])`.

# decrypt_public(CipherText, Key, Options)

(since OTP R14B)

    -spec decrypt_public(CipherText, Key, Options) -> PlainText
                            when
                                CipherText :: binary(),
                                Key :: rsa_public_key(),
                                Options :: crypto:pk_encrypt_decrypt_opts(),
                                PlainText :: binary().

Public-key decryption using the public key. See also `crypto:public_decrypt/4`

#### Warning

This is a legacy function, for security reasons do not use with rsa_pkcs1_padding. For digital signatures the use of `verify/4` together with `sign/3` is a prefered solution.

# encrypt_private(PlainText, Key)

(since OTP R14B)

    -spec encrypt_private(PlainText, Key) -> CipherText
                             when PlainText :: binary(), Key :: rsa_private_key(), CipherText :: binary().

Equivalent to `encrypt_private(PlainText, Key, [])`.

# encrypt_private(PlainText, Key, Options)

(since OTP 21.1)

    -spec encrypt_private(PlainText, Key, Options) -> CipherText
                             when
                                 PlainText :: binary(),
                                 Key :: rsa_private_key(),
                                 Options :: crypto:pk_encrypt_decrypt_opts() | custom_key_opts(),
                                 CipherText :: binary().

Public-key encryption using the private key.

See also `crypto:private_encrypt/4`. The key can, besides a standard RSA key, be a map specifing the key algorithm `rsa` and a fun to handle the encryption operation. This may be used for customized the encryption operation with for instance hardware security modules (HSM) or trusted platform modules (TPM).

#### Warning

This is a legacy function, for security reasons do not use with rsa_pkcs1_padding. For digital signatures use of `sign/3` together with `verify/4` is the prefered solution.

# encrypt_public(PlainText, Key)

(since OTP R14B)

    -spec encrypt_public(PlainText, Key) -> CipherText
                            when PlainText :: binary(), Key :: rsa_public_key(), CipherText :: binary().

Equivalent to `encrypt_public(PlainText, Key, [])`.

# encrypt_public(PlainText, Key, Options)

(since OTP 21.1)

    -spec encrypt_public(PlainText, Key, Options) -> CipherText
                            when
                                PlainText :: binary(),
                                Key :: rsa_public_key(),
                                Options :: crypto:pk_encrypt_decrypt_opts(),
                                CipherText :: binary().

Public-key encryption using the public key. See also `crypto:public_encrypt/4`.

#### Warning

This is a legacy function, for security reasons do not use with rsa_pkcs1_padding.

## PEM API

# pem_decode(PemBin)

(since OTP R14B)

    -spec pem_decode(binary()) -> [pem_entry()].

Decodes PEM binary data and returns entries as ASN.1 DER encoded entities.

Example `{ok, PemBin} = file:read_file("cert.pem"). PemEntries = public_key:pem_decode(PemBin).`

# pem_encode(PemEntries)

(since OTP R14B)

    -spec pem_encode([pem_entry()]) -> binary().

Creates a PEM binary.

# pem_entry_decode(PemEntry)

(since OTP R14B)

    -spec pem_entry_decode(PemEntry) -> term() when PemEntry :: pem_entry().

Equivalent to `pem_entry_decode(PemEntry, "")`.

# pem_entry_decode(PemEntry, Password)

(since OTP R14B)

    -spec pem_entry_decode(PemEntry, Password) -> term()
                              when PemEntry :: pem_entry(), Password :: iodata() | fun(() -> iodata()).

Decodes a PEM entry. `pem_decode/1` returns a list of PEM entries. Notice that if the PEM entry is of type 'SubjectPublickeyInfo', it is further decoded to an `rsa_public_key/0` or `dsa_public_key/0`.

Password can be either an octet string or function which returns same type.

# pem_entry_encode(Asn1Type, Entity)

(since OTP R14B)

    -spec pem_entry_encode(Asn1Type, Entity) -> pem_entry()
                              when Asn1Type :: pki_asn1_type(), Entity :: term().

Equivalent to `pem_entry_encode/3`.

# pem_entry_encode(Asn1Type, Entity, InfoPwd)

(since OTP R14B)

    -spec pem_entry_encode(Asn1Type, Entity, InfoPwd) -> pem_entry()
                              when
                                  Asn1Type :: pki_asn1_type(),
                                  Entity :: term(),
                                  InfoPwd :: {CipherInfo, Password},
                                  CipherInfo ::
                                      {Cipher :: iodata(),
                                       Salt ::
                                           binary() |
                                           {#'PBEParameter'{salt :: term(), iterationCount :: term()},
                                            digest_type()} |
                                           #'PBES2-params'{keyDerivationFunc :: term(),
                                                           encryptionScheme :: term()}},
                                  Password :: iodata().

Creates a PEM entry that can be feed to `pem_encode/1`.

If `Asn1Type` is `'SubjectPublicKeyInfo'`, `Entity` must be either an `rsa_public_key/0`, `dsa_public_key/0` or an `ecdsa_public_key/0` and this function creates the appropriate `'SubjectPublicKeyInfo'` entry.

## Sign/Verify API

# pkix_sign(Cert, Key)

(since OTP R14B)

    -spec pkix_sign(Cert, Key) -> Der
                       when
                           Cert ::
                               #'OTPTBSCertificate'{version :: term(),
                                                    serialNumber :: term(),
                                                    signature :: term(),
                                                    issuer :: term(),
                                                    validity :: term(),
                                                    subject :: term(),
                                                    subjectPublicKeyInfo :: term(),
                                                    issuerUniqueID :: term(),
                                                    subjectUniqueID :: term(),
                                                    extensions :: term()},
                           Key :: private_key(),
                           Der :: der_encoded().

Signs an 'OTPTBSCertificate'. Returns the corresponding DER-encoded certificate.

# pkix_verify(Cert, Key)

(since OTP R14B)

    -spec pkix_verify(Cert, Key) -> boolean() when Cert :: der_encoded(), Key :: public_key().

Verifies PKIX x.509 certificate signature.

# sign(Msg, DigestType, Key)

    -spec sign(Msg, DigestType, Key) -> Signature
                  when
                      Msg :: binary() | {digest, binary()},
                      DigestType :: digest_type(),
                      Key :: private_key(),
                      Signature :: binary().

Equivalent to `sign(Msg, DigestType, Key, [])`.

# sign(Msg, DigestType, Key, Options)

(since OTP 20.1)

    -spec sign(Msg, DigestType, Key, Options) -> Signature
                  when
                      Msg :: binary() | {digest, binary()},
                      DigestType :: digest_type(),
                      Key :: private_key(),
                      Options :: crypto:pk_sign_verify_opts() | custom_key_opts(),
                      Signature :: binary().

Creates a digital signature.

The `Msg` is either the binary "plain text" data to be signed or it is the hashed value of "plain text", that is, the digest. The key can, besides a standard key, be a map specifing a key algorithm and a fun that should handle the signing. This may be used for customized signing with for instance hardware security modules (HSM) or trusted platform modules (TPM).

# verify(Msg, DigestType, Signature, Key)

(since OTP R14B)

    -spec verify(Msg, DigestType, Signature, Key) -> boolean()
                    when
                        Msg :: binary() | {digest, binary()},
                        DigestType :: digest_type(),
                        Signature :: binary(),
                        Key :: public_key().

Equivalent to `verify(Msg, DigestType, Signature, Key, [])`.

# verify(Msg, DigestType, Signature, Key, Options)

(since OTP 20.1)

    -spec verify(Msg, DigestType, Signature, Key, Options) -> boolean()
                    when
                        Msg :: binary() | {digest, binary()},
                        DigestType :: digest_type(),
                        Signature :: binary(),
                        Key :: public_key(),
                        Options :: crypto:pk_sign_verify_opts().

Verifies a digital signature.

The `Msg` is either the binary "plain text" data or it is the hashed value of "plain text", that is, the digest.

## Test Data API

# pkix_test_data(ChainConf)

(since OTP 20.1)

    -spec pkix_test_data(ChainConf) -> TestConf
                            when
                                ChainConf ::
                                    #{server_chain := chain_opts(), client_chain := chain_opts()} |
                                    chain_opts(),
                                TestConf ::
                                    #{server_config := [conf_opt()], client_config := [conf_opt()]} |
                                    [conf_opt()].

Creates certificate configuration(s) consisting of certificate and its private key plus CA certificate bundle, for a client and a server, intended to facilitate automated testing of applications using X509-certificates, often through SSL/TLS. The test data can be used when you have control over both the client and the server in a test scenario.

When this function is called with a map containing client and server chain specifications; it generates both a client and a server certificate chain where the `cacerts` returned for the server contains the root cert the server should trust and the intermediate certificates the server should present to connecting clients. The root cert the server should trust is the one used as root of the client certificate chain. Vice versa applies to the `cacerts` returned for the client. The root cert(s) can either be pre-generated with pkix_test_root_cert/2 , or if options are specified; it is (they are) generated.

When this function is called with a list of certificate options; it generates a configuration with just one node certificate where `cacerts` contains the root cert and the intermediate certs that should be presented to a peer. In this case the same root cert must be used for all peers. This is useful in for example an Erlang distributed cluster where any node, towards another node, acts either as a server or as a client depending on who connects to whom. The generated certificate contains a subject altname, which is not needed in a client certificate, but makes the certificate useful for both roles.

Explanation of the options used to customize certificates in the generated chains:

- {digest, digest_type()} - Hash algorithm to be used for signing the certificate together with the key option. Defaults to sha that is sha1.

- {key, ec_params()| {rsa, Size:pos_integer(), Prime::pos_integer()} | private_key()} - Parameters to be used to call public_key:generate_key/1, to generate a key, or an existing key. Defaults to generating an ECDSA key. Note this could fail if Erlang/OTP is compiled with a very old cryptolib.

- {validity, {From::erlang:timestamp(), To::erlang:timestamp()}} - The validity period of the certificate.

- {extensions, [#'Extension'{}]} - Extensions to include in the certificate.

  Default extensions included in CA certificates if not otherwise specified are:

      [#'Extension'{extnID = ?'id-ce-keyUsage',
                    extnValue = [keyCertSign, cRLSign],
                    critical = false},
      #'Extension'{extnID = ?'id-ce-basicConstraints',
                   extnValue = #'BasicConstraints'{cA = true},
                   critical = true}]

  Default extensions included in the server peer cert if not otherwise specified are:

      [#'Extension'{extnID = ?'id-ce-keyUsage',
                    extnValue = [digitalSignature, keyAgreement],
                    critical = false},
      #'Extension'{extnID = ?'id-ce-subjectAltName',
                   extnValue = [{dNSName, Hostname}],
                   critical = false}]

  Hostname is the result of calling net_adm:localhost() in the Erlang node where this function is called.

#### Note

Note that the generated certificates and keys does not provide a formally correct PKIX-trust-chain and they cannot be used to achieve real security. This function is provided for testing purposes only.

# pkix_test_root_cert(Name, Options)

(since OTP 20.2)

    -spec pkix_test_root_cert(Name, Options) -> RootCertAndKey
                                 when
                                     Name :: string(),
                                     Options :: [cert_opt()],
                                     RootCertAndKey :: #{cert := der_encoded(), key := private_key()}.

Generates a root certificate that can be used in multiple calls to `pkix_test_data/1` when you want the same root certificate for several generated certificates.