public_key(3erl) | Erlang Module Definition | public_key(3erl) |
public_key - API module for public-key infrastructure.
Provides functions to handle public-key infrastructure, for details see public_key(7).
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").
oid() = tuple()
Object identifier, a tuple of integers as generated by the ASN.1 compiler.
der_encoded() = binary()
pki_asn1_type() =
'Certificate' |
'RSAPrivateKey' |
'RSAPublicKey' |
'DSAPrivateKey' |
'DSAPublicKey' |
'DHParameter' |
'SubjectPublicKeyInfo' |
'PrivateKeyInfo' |
'CertificationRequest' |
'CertificateList' |
'ECPrivateKey' |
'EcpkParameters'
asn1_type() = atom()
ASN.1 type present in the Public Key applications ASN.1 specifications.
pem_entry() =
{pki_asn1_type(),
der_or_encrypted_der(),
not_encrypted | cipher_info()}
der_or_encrypted_der() = binary()
cipher_info() = {cipher(), cipher_info_params()}
cipher() = string()
salt() = binary()
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).
public_key() =
rsa_public_key() |
dsa_public_key() |
ec_public_key() |
ed_public_key()
rsa_public_key() = #'RSAPublicKey'{}
dsa_public_key() = {integer(), #'Dss-Parms'{}}
ec_public_key() = {#'ECPoint'{}, ecpk_parameters_api()}
ecpk_parameters() =
{ecParameters, #'ECParameters'{}} |
{namedCurve, Oid :: tuple()}
ecpk_parameters_api() =
ecpk_parameters() |
#'ECParameters'{} |
{namedCurve, Name :: crypto:ec_named_curve()}
ed_public_key() = {ed_pub, ed25519 | ed448, Key :: binary()}
private_key() =
rsa_private_key() |
dsa_private_key() |
ec_private_key() |
ed_private_key()
rsa_private_key() = #'RSAPrivateKey'{}
dsa_private_key() = #'DSAPrivateKey'{}
ec_private_key() = #'ECPrivateKey'{}
ed_private_key() =
{ed_pri, ed25519 | ed448, Pub :: binary(), Priv :: binary()}
key_params() =
#'DHParameter'{} |
{namedCurve, oid()} |
#'ECParameters'{} |
{rsa, Size :: integer(), PubExp :: integer()}
digest_type() =
none |
crypto:rsa_digest_type() |
crypto:dss_digest_type() |
crypto:ecdsa_digest_type()
crl_reason() =
unspecified |
keyCompromise |
cACompromise |
affiliationChanged |
superseded |
cessationOfOperation |
certificateHold |
privilegeWithdrawn |
aACompromise
issuer_id() = {SerialNr :: integer(), issuer_name()}
issuer_name() = {rdnSequence, [#'AttributeTypeAndValue'{}]}
ssh_file() =
openssh_public_key |
rfc4716_public_key |
known_hosts |
auth_keys
compute_key(OthersECDHkey, MyECDHkey) -> SharedSecret
Types:
Computes shared secret.
compute_key(OthersDHkey, MyDHkey, DHparms) -> SharedSecret
Types:
Computes shared secret.
decrypt_private(CipherText, Key) -> PlainText
decrypt_private(CipherText, Key, Options) -> PlainText
Types:
Public-key decryption using the private key. See also crypto:private_decrypt/4
decrypt_public(CipherText, Key) -> PlainText
decrypt_public(CipherText, Key, Options) -> PlainText
Types:
Public-key decryption using the public key. See also crypto:public_decrypt/4
der_decode(Asn1Type, Der) -> Entity
Types:
Decodes a public-key ASN.1 DER encoded entity.
der_encode(Asn1Type, Entity) -> Der
Types:
Encodes a public-key entity with ASN.1 DER encoding.
dh_gex_group(MinSize, SuggestedSize, MaxSize, Groups) ->
{ok, {Size, Group}} | {error, term()}
Types:
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) -> CipherText
encrypt_private(PlainText, Key, Options) -> CipherText
Types:
Public-key encryption using the private key. See also crypto:private_encrypt/4.
encrypt_public(PlainText, Key) -> CipherText
encrypt_public(PlainText, Key, Options) -> CipherText
Types:
Public-key encryption using the public key. See also crypto:public_encrypt/4.
generate_key(Params :: DHparams | ECparams | RSAparams) ->
DHkeys | ECkey | RSAkey
Types:
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 :: binary()) -> [pem_entry()]
Decodes PEM binary data and returns entries as ASN.1 DER encoded entities.
Example {ok, PemBin} = file:read_file("cert.pem").
pem_encode(PemEntries :: [pem_entry()]) -> binary()
Creates a PEM binary.
pem_entry_decode(PemEntry) -> term()
pem_entry_decode(PemEntry, Password) -> term()
Types:
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, InfoPwd) -> pem_entry()
Types:
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.
pkix_decode_cert(Cert, Type) ->
#'Certificate'{} | #'OTPCertificate'{}
Types:
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, Type) -> Der
Types:
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()
Types:
Checks if IssuerCert issued Cert.
pkix_is_fixed_dh_cert(Cert) -> boolean()
Types:
Checks if a certificate is a fixed Diffie-Hellman certificate.
pkix_is_self_signed(Cert) -> boolean()
Types:
Checks if a certificate is self-signed.
pkix_issuer_id(Cert, IssuedBy) ->
{ok, issuer_id()} | {error, Reason}
Types:
Returns the issuer id.
pkix_normalize_name(Issuer) -> Normalized
Types:
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}}
Types:
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:
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.
Possible reasons for a bad certificate:
pkix_crl_issuer(CRL :: CRL | #'CertificateList'{}) -> Issuer
Types:
Returns the issuer of the CRL.
pkix_crls_validate(OTPcertificate, DPandCRLs, Options) ->
CRLstatus
Types:
Performs CRL validation. It is intended to be called from the verify fun of pkix_path_validation/3 .
Available options:
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
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()
Types:
Verify that Cert is the CRL signer.
pkix_dist_point(Cert) -> DistPoint
Types:
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
Types:
Extracts distribution points from the certificates extensions.
pkix_match_dist_point(CRL, DistPoint) -> boolean()
Types:
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(Cert, Key) -> Der
Types:
Signs an 'OTPTBSCertificate'. Returns the corresponding DER-encoded certificate.
pkix_sign_types(AlgorithmId) -> {DigestType, SignatureType}
Types:
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_test_data(Options) -> Config
pkix_test_data([chain_opts()]) -> [conf_opt()]
Types:
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:
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.
pkix_test_root_cert(Name, Options) -> RootCert
Types:
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.
pkix_verify(Cert, Key) -> boolean()
Types:
Verifies PKIX x.509 certificate signature.
pkix_verify_hostname(Cert, ReferenceIDs) -> boolean()
pkix_verify_hostname(Cert, ReferenceIDs, Opts) -> boolean()
Types:
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:
fun(....) -> true; % My special case
(_, _) -> default % all others falls back to the inherit tests end
For an example, see Hostname extraction in the User's Guide.
pkix_verify_hostname_match_fun(Protcol) -> fun(RefId |
FQDN::string(), PresentedID) -> boolean() | default
Types:
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.
sign(Msg, DigestType, Key) -> Signature
sign(Msg, DigestType, Key, Options) -> Signature
Types:
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.
ssh_decode(SshBin, Type) -> Decoded
Types:
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.
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.
ssh_encode(InData, Type) -> binary()
Types:
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.
ssh_hostkey_fingerprint(HostKey) -> string()
ssh_hostkey_fingerprint(DigestType, HostKey) -> string()
ssh_hostkey_fingerprint([DigestType], HostKey) -> [string()]
Types:
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()
verify(Msg, DigestType, Signature, Key, Options) -> boolean()
Types:
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.
short_name_hash(Name) -> string()
Types:
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.
public_key 1.6.4 | Ericsson AB |