public_key (public_key v1.11.1)

Provides functions to handle public-key infrastructure, for details see public_key(6).

Common Records and ASN.1 Types

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").

Link to this section Summary

Types

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

Cipher = "RC2-CBC" | "DES-CBC" | "DES-EDE3-CBC"

Salt could be generated with crypto:strong_rand_bytes(8).

Cipher = "RC2-CBC" | "DES-CBC" | "DES-EDE3-CBC"

Salt could be generated with crypto:strong_rand_bytes(8).

Cipher = "RC2-CBC" | "DES-CBC" | "DES-EDE3-CBC"

Salt could be generated with crypto:strong_rand_bytes(8).

Cipher = "RC2-CBC" | "DES-CBC" | "DES-EDE3-CBC"

Salt could be generated with crypto:strong_rand_bytes(8).

The tagged ed_pri format will not be returned from any public_key functions but can be used as input, should be considered deprecated.

The tagged ed_pub format will not be returned from any public_key functions but can be used as input, should be considered deprecated.

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

Cipher = "RC2-CBC" | "DES-CBC" | "DES-EDE3-CBC"

Salt could be generated with crypto:strong_rand_bytes(8).

Cipher = "RC2-CBC" | "DES-CBC" | "DES-EDE3-CBC"

Salt could be generated with crypto:strong_rand_bytes(8).

Functions

Computes shared secret.

Computes shared secret.

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

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

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

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

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.

Public-key encryption using the private key. See also crypto:private_encrypt/4.

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

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

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

Creates a PEM binary.

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() or dsa_public_key().

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

Returns the issuer of the CRL.

Verify that Cert is the CRL signer.

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

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.

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

Extracts distribution points from the certificates extensions.

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.

Translates OID to Erlang digest type

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

Checks if IssuerCert issued Cert.

Checks if a certificate is self-signed.

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

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.

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

  • TrustedCert = #'OTPCertificate'{} | der_encoded() | atom()
  • Normally a trusted certificate, but it can also be a path-validation error that can be discovered while constructing the input to this function and that is to be run through the verify_fun. Examples are unknown_ca and selfsigned_peer.
  • CertChain = [der_encoded()]
  • A list of DER-encoded certificates in trust order ending with the peer certificate.
  • Options = proplists:proplist()
  • PublicKeyInfo = {?'rsaEncryption' | ?'id-RSASSA-PSS'| ?'id-dsa', rsa_public_key() | integer(), 'NULL' | 'RSASSA-PSS-params'{} | 'Dss-Parms'{}}
  • PolicyTree = term()
  • At the moment this is always an empty list as policies are not currently supported.
  • Reason = cert_expired | invalid_issuer | invalid_signature | name_not_permitted | missing_basic_constraint | invalid_key_usage | {revoked, crl_reason()} | atom()

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.

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

Translates signature algorithm OID to Erlang digest and signature types.

Returns the X509 certificate subject id.

  • Options = #{chain_type() := chain_opts()}
  • Options for ROOT, Intermediate and Peer certs
  • chain_type() = server_chain | client_chain
  • chain_opts() = #{root := [cert_opt()] | root_cert(), peer := [cert_opt()], intermediates => [[cert_opt()]]}
  • A valid chain must have at least a ROOT and a peer cert. The root cert can be given either as a cert pre-generated by pkix_test_root_cert/2 , or as root cert generation options.
  • root_cert() = #{cert := der_encoded(), key := Key}
  • A root certificate generated by pkix_test_root_cert/2 .
  • cert_opt() = {Key, Value}
  • For available options see cert_opt() below.
  • Config = #{server_config := [conf_opt()], client_config := [conf_opt()]}
  • conf_opt() = {cert, der_encoded()} | {key, PrivateKey} |{cacerts, [der_encoded()]}
  • This is a subset of the type ssl:tls_option(). PrivateKey is what generate_key/1 returns.

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.

  • Name = string()
  • The root certificate name.
  • Options = [cert_opt()]
  • For available options see cert_opt() under pkix_test_data/1.
  • RootCert = #{cert := der_encoded(), key := Key}
  • A root certificate and key. The Key is generated by generate_key/1.

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.

Verifies PKIX x.509 certificate signature.

  • Cert = der_encoded() | #'OTPCertificate'{}
  • ReferenceIDs = [ RefID ]
  • RefID = {dns_id,string()} | {srv_id,string()} | {uri_id,string()} | {ip,inet:ip_address()|string()} | {OtherRefID,term()}}
  • OtherRefID = atom()
  • Opts = [ PvhOpt() ]
  • PvhOpt = [MatchOpt | FailCallBackOpt | FqdnExtractOpt]
  • MatchOpt = {match_fun, fun(RefId | FQDN::string(), PresentedID) -> boolean() | default}
  • PresentedID = {dNSName,string()} | {uniformResourceIdentifier,string() | {iPAddress,list(byte())} | {OtherPresId,term()}}
  • OtherPresID = atom()
  • FailCallBackOpt = {fail_callback, fun(#'OTPCertificate'{}) -> boolean()}
  • FqdnExtractOpt = {fqdn_fun, fun(RefID) -> FQDN::string() | default | undefined}

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

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

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

Creates a digital signature.

ssh_decode/2 deprecated

This function is deprecated and should not be used in new programs. Use ssh_file:decode/2 instead.

ssh_encode/2 deprecated

This function is deprecated and should not be used in new programs. Use ssh_file:encode/2 instead.

Calculates a ssh fingerprint from a public host key as openssh does.

Verifies a digital signature.

Link to this section Types

Link to this type

-type asn1_type() :: term().

Specs

asn1_type() :: atom().

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

Link to this type

-type cert_id() :: term().

Specs

cert_id() :: {SerialNr :: integer(), issuer_name()}.
Link to this type

-type cipher() :: term().

Specs

cipher() :: string().
Cipher = "RC2-CBC" | "DES-CBC" | "DES-EDE3-CBC"

Salt could be generated with crypto:strong_rand_bytes(8).

Link to this type

-type cipher_info() :: term().

Specs

cipher_info() :: {cipher(), cipher_info_params()}.
Cipher = "RC2-CBC" | "DES-CBC" | "DES-EDE3-CBC"

Salt could be generated with crypto:strong_rand_bytes(8).

Link to this type

-type cipher_info_params() :: term().

Specs

cipher_info_params() :: salt() | {#'PBEParameter'{}, digest_type()} | #'PBES2-params'{}.
Cipher = "RC2-CBC" | "DES-CBC" | "DES-EDE3-CBC"

Salt could be generated with crypto:strong_rand_bytes(8).

Link to this type

-type crl_reason() :: term().

Specs

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

-type der_encoded() :: term().

Specs

der_encoded() :: binary().
Link to this type

-type der_or_encrypted_der() :: term().

Specs

der_or_encrypted_der() :: binary().
Cipher = "RC2-CBC" | "DES-CBC" | "DES-EDE3-CBC"

Salt could be generated with crypto:strong_rand_bytes(8).

Link to this type

-type digest_type() :: term().

Specs

digest_type() ::
    none | sha1 | crypto:rsa_digest_type() | crypto:dss_digest_type() | crypto:ecdsa_digest_type().
Link to this type

-type dsa_private_key() :: term().

Specs

dsa_private_key() :: #'DSAPrivateKey'{}.
Link to this type

-type dsa_public_key() :: term().

Specs

dsa_public_key() :: {integer(), #'Dss-Parms'{}}.
Link to this type

-type ec_private_key() :: term().

Specs

ec_private_key() :: #'ECPrivateKey'{}.
Link to this type

-type ec_public_key() :: term().

Specs

ec_public_key() :: {#'ECPoint'{}, ecpk_parameters_api()}.
Link to this type

-type ecpk_parameters() :: term().

Specs

ecpk_parameters() :: {ecParameters, #'ECParameters'{}} | {namedCurve, Oid :: tuple()}.
Link to this type

-type ecpk_parameters_api() :: term().

Specs

ecpk_parameters_api() ::
    ecpk_parameters() | #'ECParameters'{} | {namedCurve, Name :: crypto:ec_named_curve()}.
Link to this type

-type ed_params() :: term().

Specs

ed_params() :: {namedCurve, {1, 3, 101, 112} | {1, 3, 101, 113}}.
Link to this type

-type ed_private_key() :: term().

Specs

ed_private_key() ::
    #'ECPrivateKey'{parameters :: ed_params()} |
    {ed_pri, ed25519 | ed448, Pub :: binary(), Priv :: binary()}.

The tagged ed_pri format will not be returned from any public_key functions but can be used as input, should be considered deprecated.

Link to this type

-type ed_public_key() :: term().

Specs

ed_public_key() :: {#'ECPoint'{}, ed_params()} | {ed_pub, ed25519 | ed448, Key :: binary()}.

The tagged ed_pub format will not be returned from any public_key functions but can be used as input, should be considered deprecated.

Link to this type

-type issuer_name() :: term().

Specs

issuer_name() :: {rdnSequence, [[#'AttributeTypeAndValue'{}]]}.
Link to this type

-type key_params() :: term().

Specs

key_params() ::
    #'DHParameter'{} |
    {namedCurve, oid()} |
    #'ECParameters'{} |
    {rsa, Size :: integer(), PubExp :: integer()}.
Link to this type

-type oid() :: term().

Specs

oid() :: tuple().

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

Link to this type

-type pem_entry() :: term().

Specs

pem_entry() :: {pki_asn1_type(), der_or_encrypted_der(), not_encrypted | cipher_info()}.
Cipher = "RC2-CBC" | "DES-CBC" | "DES-EDE3-CBC"

Salt could be generated with crypto:strong_rand_bytes(8).

Link to this type

-type pki_asn1_type() :: term().

Specs

pki_asn1_type() ::
    'Certificate' | 'RSAPrivateKey' | 'RSAPublicKey' | 'DSAPrivateKey' | 'DSAPublicKey' |
    'DHParameter' | 'SubjectPublicKeyInfo' | 'PrivateKeyInfo' | 'CertificationRequest' |
    'CertificateList' | 'ECPrivateKey' | 'EcpkParameters'.
Link to this type

-type private_key() :: term().

Specs

Link to this type

-type public_key() :: term().

Specs

Link to this type

-type rsa_private_key() :: term().

Specs

rsa_private_key() :: #'RSAPrivateKey'{}.
Link to this type

-type rsa_pss_private_key() :: term().

Specs

rsa_pss_private_key() :: {#'RSAPrivateKey'{}, #'RSASSA-PSS-params'{}}.
Link to this type

-type rsa_pss_public_key() :: term().

Specs

rsa_pss_public_key() :: {#'RSAPublicKey'{}, #'RSASSA-PSS-params'{}}.
Link to this type

-type rsa_public_key() :: term().

Specs

rsa_public_key() :: #'RSAPublicKey'{}.
Link to this type

-type salt() :: term().

Specs

salt() :: binary().
Cipher = "RC2-CBC" | "DES-CBC" | "DES-EDE3-CBC"

Salt could be generated with crypto:strong_rand_bytes(8).

Link to this type

-type ssh_file() :: term().

Specs

ssh_file() :: openssh_public_key | rfc4716_public_key | known_hosts | auth_keys.

Link to this section Functions

Link to this function

compute_key/2

(since OTP R16B01)

Specs

compute_key(OthersECDHkey, MyECDHkey) -> SharedSecret
               when
                   OthersECDHkey :: #'ECPoint'{},
                   MyECDHkey :: #'ECPrivateKey'{},
                   SharedSecret :: binary().

Computes shared secret.

Link to this function

compute_key/3

(since OTP R16B01)

Specs

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

Computes shared secret.

Link to this function

decrypt_private/2

(since OTP R14B)

Specs

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

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

Link to this function

decrypt_private/3

(since OTP R14B)

Specs

decrypt_private(CipherText, Key, Options) -> PlainText
                   when
                       CipherText :: binary(),
                       Key :: rsa_private_key(),
                       Options :: crypto:pk_encrypt_decrypt_opts(),
                       PlainText :: binary().
Link to this function

decrypt_public/2

(since OTP R14B)

Specs

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

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

Link to this function

decrypt_public/3

(since OTP R14B)

Specs

decrypt_public(CipherText, Key, Options) -> PlainText
                  when
                      CipherText :: binary(),
                      Key :: rsa_public_key(),
                      Options :: crypto:pk_encrypt_decrypt_opts(),
                      PlainText :: binary().
Link to this function

der_decode/2

(since OTP R14B)

Specs

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

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

Link to this function

der_encode/2

(since OTP R14B)

Specs

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

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

Link to this function

dh_gex_group/4

(since OTP 18.2)

Specs

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 
      
Link to this function

encrypt_private/2

(since OTP 21.1,OTP R14B)

Specs

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

Public-key encryption using the private key. See also crypto:private_encrypt/4.

Link to this function

encrypt_private/3

(since OTP 21.1,OTP R14B)

Specs

encrypt_private(PlainText, Key, Options) -> CipherText
                   when
                       PlainText :: binary(),
                       Key :: rsa_private_key(),
                       Options :: crypto:pk_encrypt_decrypt_opts(),
                       CipherText :: binary().
Link to this function

encrypt_public/2

(since OTP 21.1,OTP R14B)

Specs

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

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

Link to this function

encrypt_public/3

(since OTP 21.1,OTP R14B)

Specs

encrypt_public(PlainText, Key, Options) -> CipherText
                  when
                      PlainText :: binary(),
                      Key :: rsa_public_key(),
                      Options :: crypto:pk_encrypt_decrypt_opts(),
                      CipherText :: binary().
Link to this function

generate_key/1

(since OTP R16B01)

Specs

generate_key(DHparams | ECparams | RSAparams) -> DHkeys | ECkey | RSAkey
                when
                    DHparams :: #'DHParameter'{},
                    DHkeys :: {PublicDH :: binary(), PrivateDH :: binary()},
                    ECparams :: ecpk_parameters_api(),
                    ECkey :: #'ECPrivateKey'{},
                    RSAparams :: {rsa, Size, PubExp},
                    Size :: pos_integer(),
                    PubExp :: pos_integer(),
                    RSAkey :: #'RSAPrivateKey'{}.

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

Link to this function

pem_decode/1

(since OTP R14B)

Specs

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

Link to this function

pem_encode/1

(since OTP R14B)

Specs

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

Creates a PEM binary.

Link to this function

pem_entry_decode/1

(since OTP R14B)

Specs

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

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() or dsa_public_key().

Link to this function

pem_entry_decode/2

(since OTP R14B)

Specs

pem_entry_decode(PemEntry, Password) -> term() when PemEntry :: pem_entry(), Password :: string().
Link to this function

pem_entry_encode/2

(since OTP R14B)

Specs

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

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

If Asn1Type is 'SubjectPublicKeyInfo', Entity must be either an rsa_public_key(), dsa_public_key() or an ec_public_key() and this function creates the appropriate 'SubjectPublicKeyInfo' entry.

Link to this function

pem_entry_encode/3

(since OTP R14B)

Specs

pem_entry_encode(Asn1Type, Entity, InfoPwd) -> pem_entry()
                    when
                        Asn1Type :: pki_asn1_type(),
                        Entity :: term(),
                        InfoPwd :: {CipherInfo, Password},
                        CipherInfo :: cipher_info(),
                        Password :: string().
Link to this function

pkix_crl_issuer/1

(since OTP 17.5)

Specs

pkix_crl_issuer(CRL | #'CertificateList'{}) -> Issuer
                   when CRL :: der_encoded(), Issuer :: issuer_name().

Returns the issuer of the CRL.

Link to this function

pkix_crl_verify/2

(since OTP 17.5)

Specs

pkix_crl_verify(CRL, Cert) -> boolean()
                   when
                       CRL :: der_encoded() | #'CertificateList'{},
                       Cert :: der_encoded() | #'OTPCertificate'{}.

Verify that Cert is the CRL signer.

Link to this function

pkix_crls_validate/3

(since OTP R16B)

Specs

pkix_crls_validate(OTPcertificate, DPandCRLs, Options) -> CRLstatus
                      when
                          OTPcertificate :: #'OTPCertificate'{},
                          DPandCRLs :: [DPandCRL],
                          DPandCRL :: {DP, {DerCRL, CRL}},
                          DP :: #'DistributionPoint'{},
                          DerCRL :: der_encoded(),
                          CRL :: #'CertificateList'{},
                          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()}

The fun has the following type specification:

fun(#'DistributionPoint'{}, #'CertificateList'{},
    {rdnSequence,[#'AttributeTypeAndValue'{}]}, 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.

Link to this function

pkix_decode_cert/2

Specs

pkix_decode_cert(Cert, Type) -> #'Certificate'{} | #'OTPCertificate'{}
                    when Cert :: der_encoded(), Type :: plain | otp.

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.

Link to this function

pkix_dist_point/1

(since OTP 17.5)

Specs

pkix_dist_point(Cert) -> DistPoint
                   when
                       Cert :: der_encoded() | #'OTPCertificate'{},
                       DistPoint :: #'DistributionPoint'{}.

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

Link to this function

pkix_dist_points/1

(since OTP 17.5)

Specs

pkix_dist_points(Cert) -> DistPoints
                    when
                        Cert :: der_encoded() | #'OTPCertificate'{},
                        DistPoints :: [#'DistributionPoint'{}].

Extracts distribution points from the certificates extensions.

Link to this function

pkix_encode/3

(since OTP R14B)

Specs

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.

Link to this function

pkix_hash_type/1

(since OTP 23.0)

Specs

pkix_hash_type(HashOid :: oid()) -> DigestType :: md5 | crypto:sha1() | crypto:sha2().

Translates OID to Erlang digest type

Link to this function

pkix_is_fixed_dh_cert/1

(since OTP R14B)

Specs

pkix_is_fixed_dh_cert(Cert) -> boolean() when Cert :: der_encoded() | #'OTPCertificate'{}.

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

Link to this function

pkix_is_issuer/2

(since OTP R14B)

Specs

pkix_is_issuer(Cert, IssuerCert) -> boolean()
                  when
                      Cert :: der_encoded() | #'OTPCertificate'{} | #'CertificateList'{},
                      IssuerCert :: der_encoded() | #'OTPCertificate'{}.

Checks if IssuerCert issued Cert.

Link to this function

pkix_is_self_signed/1

(since OTP R14B)

Specs

pkix_is_self_signed(Cert) -> boolean() when Cert :: der_encoded() | #'OTPCertificate'{}.

Checks if a certificate is self-signed.

Link to this function

pkix_issuer_id/2

(since OTP R14B)

Specs

pkix_issuer_id(Cert, IssuedBy) -> {ok, ID :: cert_id()} | {error, Reason}
                  when
                      Cert :: der_encoded() | #'OTPCertificate'{},
                      IssuedBy :: self | other,
                      Reason :: term().

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

Link to this function

pkix_match_dist_point/2

(since OTP 19.0)

Specs

pkix_match_dist_point(CRL, DistPoint) -> boolean()
                         when
                             CRL :: der_encoded() | #'CertificateList'{},
                             DistPoint :: #'DistributionPoint'{}.

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.

Link to this function

pkix_normalize_name/1

(since OTP R14B)

Specs

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

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

Link to this function

pkix_path_validation(TrustedCert, CertChain, Options) -> {ok, {PublicKeyInfo, PolicyTree}} | {error, {bad_cert, Reason}}

(since OTP R16B)

Specs

pkix_path_validation(Cert :: binary() | #'OTPCertificate'{} | atom(),
                     CertChain :: [binary() | #'OTPCertificate'{}],
                     Options :: [{atom(), term()}]) ->
                        {ok, {PublicKeyInfo :: term(), PolicyTree :: term()}} |
                        {error, {bad_cert, Reason :: term()}}.
  • TrustedCert = #'OTPCertificate'{} | der_encoded() | atom()
  • Normally a trusted certificate, but it can also be a path-validation error that can be discovered while constructing the input to this function and that is to be run through the verify_fun. Examples are unknown_ca and selfsigned_peer.
  • CertChain = [der_encoded()]
  • A list of DER-encoded certificates in trust order ending with the peer certificate.
  • Options = proplists:proplist()
  • PublicKeyInfo = {?'rsaEncryption' | ?'id-RSASSA-PSS'| ?'id-dsa', rsa_public_key() | integer(), 'NULL' | 'RSASSA-PSS-params'{} | 'Dss-Parms'{}}
  • PolicyTree = term()
  • At the moment this is always an empty list as policies are not currently supported.
  • Reason = cert_expired | invalid_issuer | invalid_signature | name_not_permitted | missing_basic_constraint | invalid_key_usage | {revoked, crl_reason()} | atom()

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.

Available options:

{verify_fun, {fun(), InitialUserState::term()}

The fun must be defined as:

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

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

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

name_not_permitted

Invalid Subject Alternative Name extension.

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.

atom()

Application-specific error reason that is to be checked by the verify_fun.

Link to this function

pkix_sign/2

(since OTP R14B)

Specs

pkix_sign(Cert, Key) -> Der
             when Cert :: #'OTPTBSCertificate'{}, Key :: private_key(), Der :: der_encoded().

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

Link to this function

pkix_sign_types/1

(since OTP R16B01)

Specs

pkix_sign_types(AlgorithmId) -> {DigestType, SignatureType}
                   when
                       AlgorithmId :: oid(),
                       DigestType :: crypto:rsa_digest_type() | none,
                       SignatureType :: rsa | dsa | ecdsa.

Translates signature algorithm OID to Erlang digest and signature types.

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

Link to this function

pkix_subject_id/1

(since OTP 23.1)

Specs

pkix_subject_id(Cert) -> ID when Cert :: der_encoded() | #'OTPCertificate'{}, ID :: cert_id().

Returns the X509 certificate subject id.

Link to this function

pkix_test_data([chain_opts()]) -> [conf_opt()] pkix_test_data(Options) -> Config

(since OTP 20.1)

Specs

  • Options = #{chain_type() := chain_opts()}
  • Options for ROOT, Intermediate and Peer certs
  • chain_type() = server_chain | client_chain
  • chain_opts() = #{root := [cert_opt()] | root_cert(), peer := [cert_opt()], intermediates => [[cert_opt()]]}
  • A valid chain must have at least a ROOT and a peer cert. The root cert can be given either as a cert pre-generated by pkix_test_root_cert/2 , or as root cert generation options.
  • root_cert() = #{cert := der_encoded(), key := Key}
  • A root certificate generated by pkix_test_root_cert/2 .
  • cert_opt() = {Key, Value}
  • For available options see cert_opt() below.
  • Config = #{server_config := [conf_opt()], client_config := [conf_opt()]}
  • conf_opt() = {cert, der_encoded()} | {key, PrivateKey} |{cacerts, [der_encoded()]}
  • This is a subset of the type ssl:tls_option(). PrivateKey is what generate_key/1 returns.

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.

The cert_opt() type consists of the following options:

{digest, digest_type()}

Hash algorithm to be used for signing the certificate together with the key option. Defaults to sha that is sha1.

{key, key_params() | 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 funcion is called.

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.

Link to this function

pkix_test_root_cert(Name, Options) -> RootCert

(since OTP 20.2)

Specs

pkix_test_root_cert(Name, Options) -> RootCert
                       when
                           Name :: string(),
                           Options :: [{atom(), term()}],
                           RootCert :: pubkey_cert:test_root_cert().
  • Name = string()
  • The root certificate name.
  • Options = [cert_opt()]
  • For available options see cert_opt() under pkix_test_data/1.
  • RootCert = #{cert := der_encoded(), key := Key}
  • A root certificate and key. The Key is generated by generate_key/1.

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.

Link to this function

pkix_verify/2

(since OTP R14B)

Specs

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

Verifies PKIX x.509 certificate signature.

Link to this function

pkix_verify_hostname(Cert, ReferenceIDs) -> boolean()

(since OTP 19.3)

Specs

pkix_verify_hostname(Cert, ReferenceIDs) -> boolean()
                        when
                            Cert :: der_encoded() | #'OTPCertificate'{},
                            ReferenceIDs :: referenceIDs().
  • Cert = der_encoded() | #'OTPCertificate'{}
  • ReferenceIDs = [ RefID ]
  • RefID = {dns_id,string()} | {srv_id,string()} | {uri_id,string()} | {ip,inet:ip_address()|string()} | {OtherRefID,term()}}
  • OtherRefID = atom()
  • Opts = [ PvhOpt() ]
  • PvhOpt = [MatchOpt | FailCallBackOpt | FqdnExtractOpt]
  • MatchOpt = {match_fun, fun(RefId | FQDN::string(), PresentedID) -> boolean() | default}
  • PresentedID = {dNSName,string()} | {uniformResourceIdentifier,string() | {iPAddress,list(byte())} | {OtherPresId,term()}}
  • OtherPresID = atom()
  • FailCallBackOpt = {fail_callback, fun(#'OTPCertificate'{}) -> boolean()}
  • FqdnExtractOpt = {fqdn_fun, fun(RefID) -> FQDN::string() | default | undefined}

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 {OtherRefId,term()} is defined by the user and is passed to the match_fun, if defined. If the term in OtherRefId is a binary, it will be converted to a string.

The ip Reference ID takes an inet:ip_address() or an ip address in string format (E.g "10.0.1.1" or "1234::5678:9012") as second element.

The options are:

match_fun
The fun/2 in this option 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 fun can also return a third 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.
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 a function. This fun/1 is called when no ReferenceID matches. The return value of the fun (a boolean()) 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.
Link to this function

pkix_verify_hostname(Cert, ReferenceIDs, Opts) -> boolean()

(since OTP 19.3)

Specs

pkix_verify_hostname(Cert, ReferenceIDs, Options) -> boolean()
                        when
                            Cert :: der_encoded() | #'OTPCertificate'{},
                            ReferenceIDs :: referenceIDs(),
                            Options :: [{atom(), term()}].
Link to this function

pkix_verify_hostname_match_fun(Protcol) -> fun(RefId | FQDN::string(), PresentedID) -> boolean() | default

(since OTP 21.0)

Specs

pkix_verify_hostname_match_fun(high_level_alg()) -> match_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.

Link to this function

short_name_hash/1

(since OTP 19.0)

Specs

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.

Link to this function

sign/3

(since OTP 20.1)

Specs

sign(Msg, DigestType, Key) -> Signature
        when
            Msg :: binary() | {digest, binary()},
            DigestType :: digest_type(),
            Key :: private_key(),
            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.

Link to this function

sign/4

(since OTP 20.1)

Specs

sign(Msg, DigestType, Key, Options) -> Signature
        when
            Msg :: binary() | {digest, binary()},
            DigestType :: digest_type(),
            Key :: private_key(),
            Options :: crypto:pk_sign_verify_opts(),
            Signature :: binary().
Link to this function

ssh_decode/2

(since OTP R14B03)
This function is deprecated. public_key:ssh_decode/2 is deprecated and will be removed in OTP 26; use ssh_file:decode/2 instead.

Specs

ssh_decode(SshBin, Type) -> Decoded
              when
                  SshBin :: binary(),
                  Type :: ssh2_pubkey | OtherType | InternalType,
                  OtherType :: public_key | ssh_file(),
                  InternalType :: new_openssh,
                  Decoded :: Decoded_ssh2_pubkey | Decoded_OtherType,
                  Decoded_ssh2_pubkey :: public_key(),
                  Decoded_OtherType :: [{public_key(), Attributes}],
                  Attributes :: [{atom(), term()}].

This function is deprecated and should not be used in new programs. Use ssh_file:decode/2 instead.

Decodes an SSH file-binary. In the case of known_hosts or auth_keys, the binary can include one or more lines of the file. Returns a list of public keys and their attributes, possible attribute values depends on the file type represented by the binary.

If the Type is ssh2_pubkey, the result will be Decoded_ssh2_pubkey. Otherwise it will be Decoded_OtherType.

RFC4716 attributes - see RFC 4716.

{headers, [{string(), utf8_string()}]}

auth_key attributes - see manual page for sshd.
{comment, string()}
{options, [string()]}

{bits, integer()} - In SSH version 1 files.

known_host attributes - see manual page for sshd.
{hostnames, [string()]}
{comment, string()}

{bits, integer()} - In SSH version 1 files.

Example: {ok, SshBin} = file:read_file("known_hosts").

If Type is public_key the binary can be either an RFC4716 public key or an OpenSSH public key.

Link to this function

ssh_encode/2

(since OTP R14B03)
This function is deprecated. public_key:ssh_encode/2 is deprecated and will be removed in OTP 26; use ssh_file:encode/2 instead.

Specs

ssh_encode(InData, Type) -> binary()
              when
                  Type :: ssh2_pubkey | OtherType,
                  OtherType :: public_key | ssh_file(),
                  InData :: InData_ssh2_pubkey | OtherInData,
                  InData_ssh2_pubkey :: public_key(),
                  OtherInData :: [{Key, Attributes}],
                  Key :: public_key(),
                  Attributes :: [{atom(), term()}].

This function is deprecated and should not be used in new programs. Use ssh_file:encode/2 instead.

Encodes a list of SSH file entries (public keys and attributes) to a binary. Possible attributes depend on the file type, see ssh_decode/2 .

If the Type is ssh2_pubkey, the InData shall be InData_ssh2_pubkey. Otherwise it shall be OtherInData.

Link to this function

ssh_hostkey_fingerprint(HostKey) -> string()

(since OTP 19.2)
This function is deprecated. public_key:ssh_hostkey_fingerprint/1 is deprecated and will be removed in OTP 26; use ssh:hostkey_fingerprint/1 instead.

Specs

ssh_hostkey_fingerprint(public_key()) -> string().

Calculates a ssh fingerprint from a public host key as openssh does.

This function is deprecated and should not be used in new programs. Use ssh:hostkey_fingerprint/1 or ssh:hostkey_fingerprint/2 instead.

The algorithm in ssh_hostkey_fingerprint/1 is md5 to be compatible with older ssh-keygen commands. The string from the second variant is prepended by the algorithm name in uppercase as in newer ssh-keygen commands.

Examples:

 2> public_key:ssh_hostkey_fingerprint(Key).    
 "f5:64:a6:c1:5a:cb:9f:0a:10:46:a2:5c:3e:2f:57:84"

 3> public_key:ssh_hostkey_fingerprint(md5,Key).
 "MD5:f5:64:a6:c1:5a:cb:9f:0a:10:46:a2:5c:3e:2f:57:84"

 4> public_key:ssh_hostkey_fingerprint(sha,Key).
 "SHA1:bSLY/C4QXLDL/Iwmhyg0PGW9UbY"

 5> public_key:ssh_hostkey_fingerprint(sha256,Key).
 "SHA256:aZGXhabfbf4oxglxltItWeHU7ub3Dc31NcNw2cMJePQ"

 6> public_key:ssh_hostkey_fingerprint([sha,sha256],Key).
 ["SHA1:bSLY/C4QXLDL/Iwmhyg0PGW9UbY",
  "SHA256:aZGXhabfbf4oxglxltItWeHU7ub3Dc31NcNw2cMJePQ"]
    
Link to this function

ssh_hostkey_fingerprint([DigestType], HostKey) -> [string()] ssh_hostkey_fingerprint(DigestType, HostKey) -> string()

(since OTP 19.2)
This function is deprecated. public_key:ssh_hostkey_fingerprint/2 is deprecated and will be removed in OTP 26; use ssh:hostkey_fingerprint/2 instead.

Specs

ssh_hostkey_fingerprint(digest_type(), public_key()) -> string();
                       ([digest_type()], public_key()) -> [string()].
Link to this function

verify/4

(since OTP 20.1,OTP R14B)

Specs

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

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.

Link to this function

verify/5

(since OTP 20.1,OTP R14B)

Specs

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