public_key
API module for public-key infrastructure.
Provides functions to handle public-key infrastructure, for details see public_key(6).
DATA TYPES
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").
The following data types are used in the functions for public_key
:
oid()
Object identifier, a tuple of integers as generated by the ASN.1
compiler.
boolean() =
true | false
string() =
[bytes()]
der_encoded() =
binary()
pki_asn1_type() =
'Certificate'
| 'RSAPrivateKey'
| 'RSAPublicKey'
| 'DSAPrivateKey'
| 'DSAPublicKey'
| 'DHParameter'
| 'SubjectPublicKeyInfo'
| 'PrivateKeyInfo'
| 'CertificationRequest'
| 'CertificateList'
| 'ECPrivateKey'
| 'EcpkParameters'
pem_entry () =
{pki_asn1_type(), binary(), %% DER or encrypted DER
not_encrypted | cipher_info()}
cipher_info() =
{"RC2-CBC" | "DES-CBC" | "DES-EDE3-CBC", crypto:strong_rand_bytes(8)
| {#'PBEParameter{}, digest_type()} | #'PBES2-params'{}}
public_key() =
rsa_public_key() | dsa_public_key() | ec_public_key()
private_key() =
rsa_private_key() | dsa_private_key() | ec_private_key()
rsa_public_key() =
#'RSAPublicKey'{}
rsa_private_key() =
#'RSAPrivateKey'{}
dsa_public_key() =
{integer(), #'Dss-Parms'{}}
dsa_private_key() =
#'DSAPrivateKey'{}
ec_public_key()
= {#'ECPoint'{}, #'ECParameters'{} | {namedCurve, oid()}}
ec_private_key() =
#'ECPrivateKey'{}
public_crypt_options() =
[{rsa_pad, rsa_padding()}]
rsa_padding() =
'rsa_pkcs1_padding'
| 'rsa_pkcs1_oaep_padding'
| 'rsa_no_padding'
digest_type() =
Union of rsa_digest_type()
, dss_digest_type()
,
and ecdsa_digest_type()
.
rsa_digest_type() =
'md5' | 'sha' | 'sha224' | 'sha256' | 'sha384' | 'sha512'
dss_digest_type() =
'sha'
ecdsa_digest_type() =
'sha'| 'sha224' | 'sha256' | 'sha384' | 'sha512'
crl_reason() =
unspecified
| keyCompromise
| cACompromise
| affiliationChanged
| superseded
| cessationOfOperation
| certificateHold
| privilegeWithdrawn
| aACompromise
issuer_name() =
{rdnSequence,[#'AttributeTypeAndValue'{}]}
ssh_file() =
openssh_public_key
| rfc4716_public_key
| known_hosts
| auth_keys
Functions
compute_key(OthersKey, MyKey)->
compute_key(OthersKey, MyKey, Params)->
OthersKey = #'ECPoint'{} | binary(), MyKey = #'ECPrivateKey'{} | binary()
Params = #'DHParameter'{}
Computes shared secret.
decrypt_private(CipherText, Key) -> binary()
decrypt_private(CipherText, Key, Options) -> binary()
CipherText = binary()
Key = rsa_private_key()
Options = public_crypt_options()
Public-key decryption using the private key. See also crypto:private_decrypt/4
decrypt_public(CipherText, Key) - > binary()
decrypt_public(CipherText, Key, Options) - > binary()
CipherText = binary()
Key = rsa_public_key()
Options = public_crypt_options()
Public-key decryption using the public key. See also crypto:public_decrypt/4
der_decode(Asn1type, Der) -> term()
Asn1Type = atom()
Der = der_encoded()
Decodes a public-key ASN.1 DER encoded entity.
der_encode(Asn1Type, Entity) -> der_encoded()
Asn1Type = atom()
Entity = term()
Asn1Type
Encodes a public-key entity with ASN.1 DER encoding.
dh_gex_group(MinSize, SuggestedSize, MaxSize, Groups) -> {ok, {Size,Group}} | {error,Error}
MinSize = positive_integer()
SuggestedSize = positive_integer()
MaxSize = positive_integer()
Groups = undefined | [{Size,[{G,P}]}]
Size = positive_integer()
Group = {G,P}
G = positive_integer()
P = positive_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
encrypt_private(PlainText, Key) -> binary()
PlainText = binary()
Key = rsa_private_key()
Public-key encryption using the private key. See also crypto:private_encrypt/4.
encrypt_public(PlainText, Key) -> binary()
PlainText = binary()
Key = rsa_public_key()
Public-key encryption using the public key. See also crypto:public_encrypt/4.
generate_key(Params) -> {Public::binary(), Private::binary()} | #'ECPrivateKey'{} | #'RSAPrivateKey'{}
Params = #'DHParameter'{} | {namedCurve, oid()} | #'ECParameters'{} | {rsa, Size::integer(), PubExp::integer}
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
pem_decode(PemBin) -> [pem_entry()]
PemBin = binary()
Decodes PEM binary data and returns entries as ASN.1 DER encoded entities.
pem_encode(PemEntries) -> binary()
PemEntries = [pem_entry()]
Creates a PEM binary.
pem_entry_decode(PemEntry) -> term()
pem_entry_decode(PemEntry, Password) -> term()
PemEntry = pem_entry()
Password = string()
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()
.
pem_entry_encode(Asn1Type, Entity) -> pem_entry()
pem_entry_encode(Asn1Type, Entity, {CipherInfo, Password}) -> pem_entry()
Asn1Type = pki_asn1_type()
Entity = term()
CipherInfo = cipher_info()
Password = string()
Asn1Type
. 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.
Creates a PEM entry that can be feed to pem_encode/1
.
pkix_decode_cert(Cert, otp|plain) -> #'Certificate'{} | #'OTPCertificate'{}
Cert = der_encoded()
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.
pkix_encode(Asn1Type, Entity, otp | plain) -> der_encoded()
Asn1Type = atom()
Entity = #'Certificate'{} | #'OTPCertificate'{} | a valid subtype
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
.
pkix_is_issuer(Cert, IssuerCert) -> boolean()
Cert = der_encoded() | #'OTPCertificate'{} | #'CertificateList'{}
IssuerCert = der_encoded() | #'OTPCertificate'{}
Checks if IssuerCert
issued Cert
.
pkix_is_fixed_dh_cert(Cert) -> boolean()
Cert = der_encoded() | #'OTPCertificate'{}
Checks if a certificate is a fixed Diffie-Hellman certificate.
pkix_is_self_signed(Cert) -> boolean()
Cert = der_encoded() | #'OTPCertificate'{}
Checks if a certificate is self-signed.
pkix_issuer_id(Cert, IssuedBy) -> {ok, IssuerID} | {error, Reason}
Cert = der_encoded() | #'OTPCertificate'{}
IssuedBy = self | other
IssuerID = {integer(), issuer_name()}
Reason = term()
Returns the issuer id.
pkix_normalize_name(Issuer) -> Normalized
Issuer = issuer_name()
Normalized = issuer_name()
Normalizes an issuer name so that it can be easily compared to another issuer name.
pkix_path_validation(TrustedCert, CertChain, Options) -> {ok, {PublicKeyInfo, PolicyTree}} | {error, {bad_cert, Reason}}
TrustedCert = #'OTPCertificate'{} | der_encoded() | atom()
CertChain = [der_encoded()]
Options = proplists:proplist()
PublicKeyInfo = {?'rsaEncryption' | ?'id-dsa', rsa_public_key() | integer(), 'NULL' | 'Dss-Parms'{}}
PolicyTree = term()
Reason = cert_expired | invalid_issuer | invalid_signature | name_not_permitted | missing_basic_constraint | invalid_key_usage | {revoked, crl_reason()} | atom()
verify_fun
.
Examples are unknown_ca
and selfsigned_peer.
Performs a basic path validation according to
verify_fun
.
Available options:
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.
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:
Certificate is no longer valid as its expiration date has passed.
Certificate issuer name does not match the name of the issuer certificate in the chain.
Certificate was not signed by its issuer certificate in the chain.
Invalid Subject Alternative Name extension.
Certificate, required to have the basic constraints extension, does not have a basic constraints extension.
Certificate key is used in an invalid way according to the key-usage extension.
Certificate has been revoked.
Application-specific error reason that is to be checked by the verify_fun
.
pkix_crl_issuer(CRL) -> issuer_name()
CRL = der_encoded() | #'CertificateList'{}
Returns the issuer of the CRL
.
pkix_crls_validate(OTPCertificate, DPAndCRLs, Options) -> CRLStatus()
OTPCertificate = #'OTPCertificate'{}
DPAndCRLs = [{DP::#'DistributionPoint'{}, {DerCRL::der_encoded(), CRL::#'CertificateList'{}}}]
Options = proplists:proplist()
CRLStatus() = valid | {bad_cert, revocation_status_undetermined} | {bad_cert, {revoked, crl_reason()}}
Performs CRL validation. It is intended to be called from the verify fun of pkix_path_validation/3 .
Available options:
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
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}
pkix_crl_verify(CRL, Cert) -> boolean()
CRL = der_encoded() | #'CertificateList'{}
Cert = der_encoded() | #'OTPCertificate'{}
Verify that Cert
is the CRL
signer.
pkix_dist_point(Cert) -> DistPoint
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
pkix_dist_points(Cert) -> DistPoints
Cert = der_encoded() | #'OTPCertificate'{}
DistPoints = [#'DistributionPoint'{}]
Extracts distribution points from the certificates extensions.
pkix_match_dist_point(CRL, DistPoint) -> boolean()
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.
pkix_sign(#'OTPTBSCertificate'{}, Key) -> der_encoded()
Key = rsa_private_key() | dsa_private_key()
Signs an 'OTPTBSCertificate'. Returns the corresponding DER-encoded certificate.
pkix_sign_types(AlgorithmId) -> {DigestType, SignatureType}
AlgorithmId = oid()
DigestType = rsa_digest_type() | dss_digest_type()
SignatureType = rsa | dsa | ecdsa
Translates signature algorithm OID to Erlang digest and signature types.
pkix_verify(Cert, Key) -> boolean()
Cert = der_encoded()
Key = rsa_public_key() | dsa_public_key() | ec_public_key()
Verifies PKIX x.509 certificate signature.
pkix_verify_hostname(Cert, ReferenceIDs) -> boolean()
pkix_verify_hostname(Cert, ReferenceIDs, Opts) -> boolean()
Cert = der_encoded() | #'OTPCertificate'{}
ReferenceIDs = [ RefID ]
RefID = {IdType,string()}
IdType = dns_id | srv_id | uri_id
Opts = [ PvhOpt() ]
PvhOpt = [MatchOpt | FailCallBackOpt | FqdnExtractOpt]
MatchOpt = {fun(RefId | FQDN::string(), PresentedID) -> boolean() | default}
PresentedID = {dNSName,string()} | {uniformResourceIdentifier,string()}
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 conforms with the Expected Identifier that the client wants to connect to. This functions is intended to be added as an extra client check to the peer certificate when performing public_key:pkix_path_validation/3
See
sign(Msg, DigestType, Key) -> binary()
Msg = binary() | {digest,binary()}
DigestType = rsa_digest_type() | dss_digest_type() | ecdsa_digest_type()
Key = rsa_private_key() | dsa_private_key() | ec_private_key()
Msg
is either the binary "plain text" data to be
signed or it is the hashed value of "plain text", that is, the
digest.Creates a digital signature.
ssh_decode(SshBin, Type) -> [{public_key(), Attributes::list()}]
SshBin = binary()
Type = public_key | ssh_file()
{ok, SshBin} = file:read_file("known_hosts")
.Type
is public_key
the binary can be either
an RFC4716 public key or an OpenSSH public key.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.
{headers, [{string(), utf8_string()}]}
{bits, integer()} - In SSH version 1 files.
{bits, integer()} - In SSH version 1 files.
ssh_encode([{Key, Attributes}], Type) -> binary()
Key = public_key()
Attributes = list()
Type = ssh_file()
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 .
ssh_hostkey_fingerprint(HostKey) -> string()
ssh_hostkey_fingerprint(DigestType, HostKey) -> string()
ssh_hostkey_fingerprint([DigestType], HostKey) -> [string()]
Key = public_key()
DigestType = digest_type()
Calculates a ssh fingerprint from a public host key as openssh does.
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"]
verify(Msg, DigestType, Signature, Key) -> boolean()
Msg = binary() | {digest,binary()}
DigestType = rsa_digest_type() | dss_digest_type() | ecdsa_digest_type()
Signature = binary()
Key = rsa_public_key() | dsa_public_key() | ec_public_key()
Msg
is either the binary "plain text" data
or it is the hashed value of "plain text", that is, the digest.Verifies a digital signature.
short_name_hash(Name) -> string()
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.