View Source crypto (crypto v5.5.2)

Crypto Functions

This module provides a set of cryptographic functions.

Note

The actual supported algorithms and features depends on their availability in the actual libcrypto used. See the crypto (App) about dependencies.

Enabling FIPS mode will also disable algorithms and features.

The CRYPTO User's Guide has more information on FIPS, Engines and Algorithm Details like key lengths.

Exceptions

Atoms - the older style

The exception error:badarg signifies that one or more arguments are of wrong data type, or are otherwise badly formed.

The exception error:notsup signifies that the algorithm is known but is not supported by current underlying libcrypto or explicitly disabled when building that.

For a list of supported algorithms, see supports(ciphers).

3-tuples - the new style

The exception is:

error:{Tag, C_FileInfo, Description}

Tag = badarg | notsup | error
C_FileInfo = term()    % Usually only useful for the OTP maintainer
Description = string() % Clear text, sometimes only useful for the OTP maintainer

The exception tags are:

  • badarg - Signifies that one or more arguments are of wrong data type or are otherwise badly formed.

  • notsup - Signifies that the algorithm is known but is not supported by current underlying libcrypto or explicitly disabled when building that one.

  • error - An error condition that should not occur, for example a memory allocation failed or the underlying cryptolib returned an error code, for example "Can't initialize context, step 1". Those text usually needs searching the C-code to be understood.

Usually there are more information in the call stack about which argument caused the exception and what the values where.

To catch the exception, use for example:

try crypto:crypto_init(Ciph, Key, IV, true)
    catch
        error:{Tag, _C_FileInfo, Description} ->
            do_something(......)
         .....
end

Summary

Types: Ciphers

Ciphers known by the CRYPTO application.

Selects encryption ({encrypt,true}) or decryption ({encrypt,false}).

Equivalent to crypto_opt().

The cryptolib_padding are paddings that may be present in the underlying cryptolib linked to the Erlang/OTP crypto app.

Erlang/OTP adds a either padding of zeroes or padding with random bytes.

This option handles padding in the last block. If not set, no padding is done and any bytes in the last unfilled block is silently discarded.

Types: Elliptic Curves

Curve definition details.

Parametric curve definition.

Equivalent to ec_curve().

Equivalent to ec_basis().

Note that some curves are disabled if FIPS is enabled.

Types: Keys

Always binary/0 when used as return value

Types: Public/Private Keys

dss_public() = [P, Q, G, Y]

Where P, Q and G are the dss parameters and Y is the public key.

Equivalent to dss_private().

rsa_public() = [E, N]
rsa_private() = [E, N, D] | [E, N, D, P1, P2, E1, E2, C]

Where E is the public exponent, N is public modulus and D is the private exponent. The longer key format contains redundant information that will make the calculation faster. P1 and P2 are first and second prime factors. E1 and E2 are first and second exponents. C is the CRT coefficient. The terminology is taken from RFC 3447.

Equivalent to rsa_params().

Equivalent to rsa_params().

Where Verifier is v, Generator is g and Prime isN, DerivedKey is X, and Scrambler is u (optional will be generated if not provided) from SRP design Version = '3' | '6' | '6a'

srp_public() = key_integer()

Where is A or B from SRP design

Equivalent to srp_private().

Types: Public Key Ciphers

Algorithms for public key encrypt/decrypt. Only RSA is supported.

Those option forms are kept only for compatibility and should not be used in new code.

Equivalent to rsa_padding().

Options for public key encrypt/decrypt. Only RSA is supported.

Types: Diffie-Hellman Keys and parameters

dh_params() = [P, G] | [P, G, PrivateKeyBitLength]

Equivalent to dh_private().

Equivalent to ecdh_params().

Equivalent to ecdh_params().

Types: Types for Engines

Pre and Post commands for engine_load/3 and /4.

The result of a call to engine_load/3.

Identifies the key to be used. The format depends on the loaded engine. It is passed to the ENGINE_load_(private|public)_key functions in libcrypto.

The password of the key stored in an engine.

Types: Internal data types

Equivalent to mac_state().

Equivalent to mac_state().

Contexts with an internal state that should not be manipulated but passed between function calls.

Cipher API

Finalize a streaming encryptions or decryptions operation and delivers the final bytes of the final block.

Return information about a crypto_state/0.

Initialize the state for a streaming encryption or decryption operation.

Initialize the state for a streaming encryptions or decryptions operation.

Do a complete encrypt or decrypt of the full text.

Do a complete encrypt or decrypt of the full text.

Do a complete encrypt or decrypt with an AEAD cipher of the full text.

Add data to a streaming encryption or decryption operation.

Hash API

Compute a message digest.

Finalize a streaming hash calculation.

Initialize the state for a streaming hash digest calculation.

Add data to a streaming digest calculation.

Compute a message digest for an xof_algorithm.

MAC API

Compute a poly1305 MAC (Message Authentication Code).

Compute a MAC (Message Authentication Code).

Finalize a streaming MAC operation.

Finalize a MAC operation with a custom length.

Initialize a state for streaming poly1305 MAC calculation.

Initialize the state for streaming MAC calculation.

Add data to a streaming MAC calculation.

Compute a poly1305 MAC (Message Authentication Code) with a limited length.

Compute a MAC (Message Authentication Code) with a limited length.

Key API

Compute the shared secret from the private key and the other party's public key.

Generate a public key.

Random API

Create a state object for random number generation, in order to generate cryptographically strong random numbers (based on OpenSSL's BN_rand_range).

Set the seed for PRNG to the given binary.

Create a state object for random number generation, in order to generate cryptographically strong random numbers.

Creates a state object for random number generation, in order to generate cryptographically unpredictable random numbers.

Create a state object for random number generation, in order to generate cryptographically strongly random numbers.

Create a state object for random number generation, in order to generate cryptographically unpredictable random numbers.

Create a state object for random number generation, in order to generate cryptographically strongly random numbers (based on OpenSSL's BN_rand_range). See also rand:seed_s/1.

rand_uniform/2 deprecated

Generate a random integer number.

Generate bytes with randomly uniform values 0..255.

Utility Functions

Convert binary representation, of an integer, to an Erlang integer.

Get information about a cipher algorithm.

Return the defining parameters of a elliptic curve.

Return all supported named elliptic curves.

Enable or disable FIPs mode.

Perform bit-wise XOR (exclusive or) on the data supplied.

Compare two binaries in constant time, such as results of HMAC computations.

Get information about a hash algorithm.

Get information about crypto and the OpenSSL backend.

Get information about the operating status of FIPS.

Get the name and version of the libraries used by crypto.

Compute the function N^P mod M.

Get which crypto algorithms that are supported by the underlying libcrypto library.

Engine API

Add the engine to OpenSSL's internal list.

Get a reference to an already loaded engine with EngineId. An error tuple is returned if the engine can't be unloaded.

Send ctrl commands to an OpenSSL engine.

Send ctrl commands to an OpenSSL engine.

Return a list of all possible engine methods.

Return the ID for the engine, or an empty binary if there is no id set.

Return the name (eg a description) for the engine, or an empty binary if there is no name set.

List the id's of all engines in OpenSSL's internal list.

Register engine to handle some type of methods, for example engine_method_digests.

Remove the engine from OpenSSL's internal list.

Unload an OpenSSL engine.

Unregister engine so it don't handle some type of methods.

Load a dynamic engine if not already done.

PKCS #5 PBKDF2 (Password-Based Key Derivation Function 2) in combination with HMAC.

Fetch public key from a private key stored in an Engine.

Types: Ciphers

Link to this type

cipher()

View Source (not exported)
-type cipher() :: cipher_no_iv() | cipher_iv() | cipher_aead().
Link to this type

cipher_aead()

View Source (not exported)
-type cipher_aead() ::
          aes_128_ccm | aes_192_ccm | aes_256_ccm | aes_ccm | aes_128_gcm | aes_192_gcm | aes_256_gcm |
          aes_gcm | sm4_gcm | sm4_ccm | chacha20_poly1305.

Ciphers known by the CRYPTO application.

Note that this list might be reduced if the underlying libcrypto does not support all of them.

Link to this type

cipher_iv()

View Source (not exported)
-type cipher_iv() ::
          aes_128_cbc | aes_192_cbc | aes_256_cbc | aes_cbc | aes_128_ofb | aes_192_ofb | aes_256_ofb |
          aes_128_cfb128 | aes_192_cfb128 | aes_256_cfb128 | aes_cfb128 | aes_128_cfb8 | aes_192_cfb8 |
          aes_256_cfb8 | aes_cfb8 | aes_128_ctr | aes_192_ctr | aes_256_ctr | aes_ctr | sm4_cbc |
          sm4_ofb | sm4_cfb | sm4_ctr | blowfish_cbc | blowfish_cfb64 | blowfish_ofb64 | chacha20 |
          des_ede3_cbc | des_ede3_cfb | des_cbc | des_cfb | rc2_cbc.
Link to this type

cipher_no_iv()

View Source (not exported)
-type cipher_no_iv() ::
          aes_128_ecb | aes_192_ecb | aes_256_ecb | aes_ecb | blowfish_ecb | des_ecb | sm4_ecb | rc4.
Link to this type

crypto_opt()

View Source (not exported)
-type crypto_opt() :: {encrypt, boolean()} | {padding, padding()}.

Selects encryption ({encrypt,true}) or decryption ({encrypt,false}).

Link to this type

crypto_opts()

View Source (not exported)
-type crypto_opts() :: boolean() | [crypto_opt()].

Equivalent to crypto_opt().

Link to this type

cryptolib_padding()

View Source (not exported)
-type cryptolib_padding() :: none | pkcs_padding.

The cryptolib_padding are paddings that may be present in the underlying cryptolib linked to the Erlang/OTP crypto app.

For OpenSSL, see the OpenSSL documentation. and find EVP_CIPHER_CTX_set_padding() in cryptolib for your linked version.

Link to this type

otp_padding()

View Source (not exported)
-type otp_padding() :: zero | random.

Erlang/OTP adds a either padding of zeroes or padding with random bytes.

Link to this type

padding()

View Source (not exported)
-type padding() :: cryptolib_padding() | otp_padding().

This option handles padding in the last block. If not set, no padding is done and any bytes in the last unfilled block is silently discarded.

Types: Digests and hash

Link to this type

blake2()

View Source (not exported)
-type blake2() :: blake2b | blake2s.
Link to this type

cmac_cipher_algorithm()

View Source (not exported)
-type cmac_cipher_algorithm() ::
          aes_128_cbc | aes_192_cbc | aes_256_cbc | aes_cbc | blowfish_cbc | des_cbc | des_ede3_cbc |
          rc2_cbc.
Link to this type

compatibility_only_hash()

View Source (not exported)
-type compatibility_only_hash() :: md5 | md4.

The compatibility_only_hash/0 algorithms are recommended only for compatibility with existing applications.

-type dss_digest_type() :: sha1() | sha2().
-type ecdsa_digest_type() :: sha1() | sha2().
Link to this type

hash_algorithm()

View Source (not exported)
-type hash_algorithm() ::
          sha1() | sha2() | sha3() | sha3_xof() | blake2() | ripemd160 | sm3 | compatibility_only_hash().
Link to this type

hash_xof_algorithm()

View Source (not exported)
-type hash_xof_algorithm() :: sha3_xof().
Link to this type

hmac_hash_algorithm()

View Source (not exported)
-type hmac_hash_algorithm() :: sha1() | sha2() | sha3() | sm3 | compatibility_only_hash().
-type rsa_digest_type() :: sha1() | sha2() | md5 | ripemd160.
-type sha1() :: sha.

Equivalent to blake2().

-type sha2() :: sha224 | sha256 | sha384 | sha512.

Equivalent to blake2().

-type sha3() :: sha3_224 | sha3_256 | sha3_384 | sha3_512.

Equivalent to blake2().

Link to this type

sha3_xof()

View Source (not exported)
-type sha3_xof() :: shake128 | shake256.

Equivalent to blake2().

Types: Elliptic Curves

Link to this type

ec_basis()

View Source (not exported)
-type ec_basis() ::
          {tpbasis, K :: non_neg_integer()} |
          {ppbasis, K1 :: non_neg_integer(), K2 :: non_neg_integer(), K3 :: non_neg_integer()} |
          onbasis.

Curve definition details.

Link to this type

ec_characteristic_two_field()

View Source (not exported)
-type ec_characteristic_two_field() :: {characteristic_two_field, M :: integer(), Basis :: ec_basis()}.

Equivalent to ec_basis().

Link to this type

ec_curve()

View Source (not exported)
-type ec_curve() :: {A :: binary(), B :: binary(), Seed :: none | binary()}.

Parametric curve definition.

Link to this type

ec_explicit_curve()

View Source (not exported)
-type ec_explicit_curve() ::
          {Field :: ec_field(),
           Curve :: ec_curve(),
           BasePoint :: binary(),
           Order :: binary(),
           CoFactor :: none | binary()}.

Equivalent to ec_curve().

Link to this type

ec_field()

View Source (not exported)
-type ec_field() :: ec_prime_field() | ec_characteristic_two_field().

Equivalent to ec_curve().

-type ec_named_curve() ::
          brainpoolP160r1 | brainpoolP160t1 | brainpoolP192r1 | brainpoolP192t1 | brainpoolP224r1 |
          brainpoolP224t1 | brainpoolP256r1 | brainpoolP256t1 | brainpoolP320r1 | brainpoolP320t1 |
          brainpoolP384r1 | brainpoolP384t1 | brainpoolP512r1 | brainpoolP512t1 | c2pnb163v1 |
          c2pnb163v2 | c2pnb163v3 | c2pnb176v1 | c2pnb208w1 | c2pnb272w1 | c2pnb304w1 | c2pnb368w1 |
          c2tnb191v1 | c2tnb191v2 | c2tnb191v3 | c2tnb239v1 | c2tnb239v2 | c2tnb239v3 | c2tnb359v1 |
          c2tnb431r1 | ipsec3 | ipsec4 | prime192v1 | prime192v2 | prime192v3 | prime239v1 |
          prime239v2 | prime239v3 | prime256v1 | secp112r1 | secp112r2 | secp128r1 | secp128r2 |
          secp160k1 | secp160r1 | secp160r2 | secp192k1 | secp192r1 | secp224k1 | secp224r1 |
          secp256k1 | secp256r1 | secp384r1 | secp521r1 | sect113r1 | sect113r2 | sect131r1 |
          sect131r2 | sect163k1 | sect163r1 | sect163r2 | sect193r1 | sect193r2 | sect233k1 |
          sect233r1 | sect239k1 | sect283k1 | sect283r1 | sect409k1 | sect409r1 | sect571k1 |
          sect571r1 | wtls1 | wtls10 | wtls11 | wtls12 | wtls3 | wtls4 | wtls5 | wtls6 | wtls7 | wtls8 |
          wtls9.

Equivalent to edwards_curve_ed().

Link to this type

ec_prime_field()

View Source (not exported)
-type ec_prime_field() :: {prime_field, Prime :: integer()}.

Equivalent to ec_basis().

Link to this type

edwards_curve_dh()

View Source (not exported)
-type edwards_curve_dh() :: x25519 | x448.

Equivalent to edwards_curve_ed().

Link to this type

edwards_curve_ed()

View Source (not exported)
-type edwards_curve_ed() :: ed25519 | ed448.

Note that some curves are disabled if FIPS is enabled.

Types: Keys

Link to this type

key_integer()

View Source (not exported)
-type key_integer() :: integer() | binary().

Always binary/0 when used as return value

Types: Public/Private Keys

Link to this type

dss_private()

View Source (not exported)
-type dss_private() :: [key_integer()].
dss_public() = [P, Q, G, Y]

Where P, Q and G are the dss parameters and Y is the public key.

dss_private() = [P, Q, G, X]

Where P, Q and G are the dss parameters and X is the private key.

Link to this type

dss_public()

View Source (not exported)
-type dss_public() :: [key_integer()].

Equivalent to dss_private().

Link to this type

ecdsa_params()

View Source (not exported)
-type ecdsa_params() :: ec_named_curve() | ec_explicit_curve().
Link to this type

ecdsa_private()

View Source (not exported)
-type ecdsa_private() :: key_integer().

Equivalent to ecdsa_params().

Link to this type

ecdsa_public()

View Source (not exported)
-type ecdsa_public() :: key_integer().

Equivalent to ecdsa_params().

Link to this type

eddsa_params()

View Source (not exported)
-type eddsa_params() :: edwards_curve_ed().
Link to this type

eddsa_private()

View Source (not exported)
-type eddsa_private() :: key_integer().

Equivalent to eddsa_params().

Link to this type

eddsa_public()

View Source (not exported)
-type eddsa_public() :: key_integer().

Equivalent to eddsa_params().

Link to this type

rsa_params()

View Source (not exported)
-type rsa_params() :: {ModulusSizeInBits :: integer(), PublicExponent :: key_integer()}.
rsa_public() = [E, N]
rsa_private() = [E, N, D] | [E, N, D, P1, P2, E1, E2, C]

Where E is the public exponent, N is public modulus and D is the private exponent. The longer key format contains redundant information that will make the calculation faster. P1 and P2 are first and second prime factors. E1 and E2 are first and second exponents. C is the CRT coefficient. The terminology is taken from RFC 3447.

Link to this type

rsa_private()

View Source (not exported)
-type rsa_private() :: [key_integer()].

Equivalent to rsa_params().

Link to this type

rsa_public()

View Source (not exported)
-type rsa_public() :: [key_integer()].

Equivalent to rsa_params().

Link to this type

srp_comp_params()

View Source (not exported)
-type srp_comp_params() :: {user, srp_user_comp_params()} | {host, srp_host_comp_params()}.

Equivalent to srp_host_comp_params().

Link to this type

srp_gen_params()

View Source (not exported)
-type srp_gen_params() :: {user, srp_user_gen_params()} | {host, srp_host_gen_params()}.

Equivalent to srp_host_comp_params().

Link to this type

srp_host_comp_params()

View Source (not exported)
-type srp_host_comp_params() :: [binary() | atom()].

Where Verifier is v, Generator is g and Prime isN, DerivedKey is X, and Scrambler is u (optional will be generated if not provided) from SRP design Version = '3' | '6' | '6a'

Link to this type

srp_host_gen_params()

View Source (not exported)
-type srp_host_gen_params() :: [binary() | atom() | list()].

Equivalent to srp_host_comp_params().

Link to this type

srp_private()

View Source (not exported)
-type srp_private() :: key_integer().
srp_public() = key_integer()

Where is A or B from SRP design

srp_private() = key_integer()

Where is a or b from SRP design

Link to this type

srp_public()

View Source (not exported)
-type srp_public() :: key_integer().

Equivalent to srp_private().

Link to this type

srp_user_comp_params()

View Source (not exported)
-type srp_user_comp_params() :: [binary() | atom()].

Equivalent to srp_host_comp_params().

Link to this type

srp_user_gen_params()

View Source (not exported)
-type srp_user_gen_params() :: [binary() | atom() | list()].

Equivalent to srp_host_comp_params().

Types: Public Key Ciphers

Link to this type

pk_encrypt_decrypt_algs()

View Source (not exported)
-type pk_encrypt_decrypt_algs() :: rsa.

Algorithms for public key encrypt/decrypt. Only RSA is supported.

Link to this type

pk_encrypt_decrypt_opts()

View Source
-type pk_encrypt_decrypt_opts() :: [rsa_opt()] | rsa_compat_opts().

Equivalent to rsa_padding().

Link to this type

rsa_compat_opts()

View Source (not exported)
-type rsa_compat_opts() :: [{rsa_pad, rsa_padding()}] | rsa_padding().

Those option forms are kept only for compatibility and should not be used in new code.

Link to this type

rsa_opt()

View Source (not exported)
-type rsa_opt() ::
          {rsa_padding, rsa_padding()} |
          {signature_md, atom()} |
          {rsa_mgf1_md, sha} |
          {rsa_oaep_label, binary()} |
          {rsa_oaep_md, sha}.

Equivalent to rsa_padding().

Link to this type

rsa_padding()

View Source (not exported)
-type rsa_padding() :: rsa_pkcs1_padding | rsa_pkcs1_oaep_padding | rsa_x931_padding | rsa_no_padding.

Options for public key encrypt/decrypt. Only RSA is supported.

Warning

The RSA options are experimental.

The exact set of options and there syntax may be changed without prior notice.

Types: Public Key Sign and Verify

Link to this type

pk_sign_verify_algs()

View Source (not exported)
-type pk_sign_verify_algs() :: rsa | dss | ecdsa | eddsa.

Algorithms for sign and verify.

-type pk_sign_verify_opts() :: [rsa_sign_verify_opt()].

Equivalent to rsa_sign_verify_padding().

Link to this type

rsa_sign_verify_opt()

View Source (not exported)
-type rsa_sign_verify_opt() ::
          {rsa_padding, rsa_sign_verify_padding()} |
          {rsa_pss_saltlen, integer()} |
          {rsa_mgf1_md, sha2()}.

Equivalent to rsa_sign_verify_padding().

Link to this type

rsa_sign_verify_padding()

View Source (not exported)
-type rsa_sign_verify_padding() ::
          rsa_pkcs1_padding | rsa_pkcs1_pss_padding | rsa_x931_padding | rsa_no_padding.

Options for sign and verify.

Warning

The RSA options are experimental.

The exact set of options and there syntax may be changed without prior notice.

Types: Diffie-Hellman Keys and parameters

Link to this type

dh_params()

View Source (not exported)
-type dh_params() :: [key_integer()].
dh_params() = [P, G] | [P, G, PrivateKeyBitLength]
-type dh_private() :: key_integer().
-type dh_public() :: key_integer().

Equivalent to dh_private().

Link to this type

ecdh_params()

View Source (not exported)
-type ecdh_params() :: ec_named_curve() | edwards_curve_dh() | ec_explicit_curve().
Link to this type

ecdh_private()

View Source (not exported)
-type ecdh_private() :: key_integer().

Equivalent to ecdh_params().

Link to this type

ecdh_public()

View Source (not exported)
-type ecdh_public() :: key_integer().

Equivalent to ecdh_params().

Types: Types for Engines

Link to this type

engine_cmnd()

View Source (not exported)
-type engine_cmnd() :: {unicode:chardata(), unicode:chardata()}.

Pre and Post commands for engine_load/3 and /4.

Link to this type

engine_key_ref()

View Source (not exported)
-type engine_key_ref() ::
          #{engine := engine_ref(), key_id := key_id(), password => password(), term() => term()}.

Equivalent to engine_ref().

Link to this type

engine_method_type()

View Source (not exported)
-type engine_method_type() ::
          engine_method_rsa | engine_method_dsa | engine_method_dh | engine_method_rand |
          engine_method_ecdh | engine_method_ecdsa | engine_method_ciphers | engine_method_digests |
          engine_method_store | engine_method_pkey_meths | engine_method_pkey_asn1_meths |
          engine_method_ec.
-type engine_ref() :: term().

The result of a call to engine_load/3.

-type key_id() :: string() | binary().

Identifies the key to be used. The format depends on the loaded engine. It is passed to the ENGINE_load_(private|public)_key functions in libcrypto.

-type password() :: string() | binary().

The password of the key stored in an engine.

Types: Internal data types

-opaque crypto_state()

Equivalent to mac_state().

-opaque hash_state()

Equivalent to mac_state().

-opaque mac_state()

Contexts with an internal state that should not be manipulated but passed between function calls.

Types

Link to this type

crypto_integer()

View Source (not exported)
-type crypto_integer() :: binary() | integer().
Link to this type

rand_cache_seed()

View Source (not exported)
-type rand_cache_seed() :: nonempty_improper_list(non_neg_integer(), binary()).

Cipher API

Link to this function

crypto_final(State)

View Source (since OTP 23.0)
-spec crypto_final(State) -> FinalResult when State :: crypto_state(), FinalResult :: binary().

Finalize a streaming encryptions or decryptions operation and delivers the final bytes of the final block.

The data returned from this function may be empty if no padding was enabled in crypto_init/3 or crypto_init/4.

Uses the 3-tuple style for error handling.

Link to this function

crypto_get_data(State)

View Source (since OTP 23.0)
-spec crypto_get_data(State) -> Result when State :: crypto_state(), Result :: map().

Return information about a crypto_state/0.

The information returned is a map, which currently contains at least:

  • size - The number of bytes encrypted or decrypted so far.

  • padding_size - After a call to crypto_final/1 it contains the number of bytes padded. Otherwise 0.

  • padding_type - The type of the padding as provided in the call to crypto_init/3 or crypto_init/4.

  • encrypt - Is true if encryption is performed. It is false otherwise.

Uses the 3-tuple style for error handling.

Link to this function

crypto_init(Cipher, Key, FlagOrOptions)

View Source (since OTP 22.0)
-spec crypto_init(Cipher, Key, FlagOrOptions) -> State
                     when
                         Cipher :: cipher_no_iv(),
                         Key :: iodata(),
                         FlagOrOptions :: crypto_opts() | boolean(),
                         State :: crypto_state().

Initialize the state for a streaming encryption or decryption operation.

Equivalent to the call crypto_init(Cipher, Key, <<>>, FlagOrOptions). It is intended for ciphers without an IV (nounce).

Uses the 3-tuple style for error handling.

Link to this function

crypto_init(Cipher, Key, IV, FlagOrOptions)

View Source (since OTP 22.0)
-spec crypto_init(Cipher, Key, IV, FlagOrOptions) -> State
                     when
                         Cipher :: cipher_iv(),
                         Key :: iodata(),
                         IV :: iodata(),
                         FlagOrOptions :: crypto_opts(),
                         State :: crypto_state().

Initialize the state for a streaming encryptions or decryptions operation.

The returned state should be used as argument to crypto_update/2 and crypto_final/1 to do the actual encryption or decryption.

If IV = <<>>, no IV is used. This is intended for ciphers without an IV (nounce). See crypto_init/3.

For encryption, set the FlagOrOptions to true or [{encrypt,true}]. For decryption, set it to false or [{encrypt,false}].

Padding could be enabled with the option {padding,Padding}. The cryptolib_padding enables pkcs_padding or no padding (none). The paddings zero or random fills the last part of the last block with zeroes or random bytes. If the last block is already full, nothing is added.

In decryption, the cryptolib_padding removes such padding, if present. The otp_padding is not removed - it has to be done elsewhere.

If padding is {padding,none} or not specified and the total data from all subsequent crypto_updates does not fill the last block fully, that last data is lost. In case of {padding,none} there will be an error in this case. If padding is not specified, the bytes of the unfilled block is silently discarded.

The actual padding is performed by crypto_final/1.

For blocksizes call cipher_info/1.

Uses the 3-tuple style for error handling.

See examples in the User's Guide.

Link to this function

crypto_one_time(Cipher, Key, Data, FlagOrOptions)

View Source (since OTP 22.0)
-spec crypto_one_time(Cipher, Key, Data, FlagOrOptions) -> Result
                         when
                             Cipher :: cipher_no_iv(),
                             Key :: iodata(),
                             Data :: iodata(),
                             FlagOrOptions :: crypto_opts() | boolean(),
                             Result :: binary().

Do a complete encrypt or decrypt of the full text.

As crypto_one_time/5 but for ciphers without IVs.

Uses the 3-tuple style for error handling.

Link to this function

crypto_one_time(Cipher, Key, IV, Data, FlagOrOptions)

View Source (since OTP 22.0)
-spec crypto_one_time(Cipher, Key, IV, Data, FlagOrOptions) -> Result
                         when
                             Cipher :: cipher_iv(),
                             Key :: iodata(),
                             IV :: iodata(),
                             Data :: iodata(),
                             FlagOrOptions :: crypto_opts() | boolean(),
                             Result :: binary().

Do a complete encrypt or decrypt of the full text.

Argument Data is the text to be encrypted or decrypted.

For encryption, set the FlagOrOptions to true. For decryption, set it to false. For setting other options, see crypto_init/4.

Uses the 3-tuple style for error handling.

See examples in the User's Guide.

Link to this function

crypto_one_time_aead(Cipher, Key, IV, InText, AAD, EncFlag)

View Source (since OTP 22.0)
-spec crypto_one_time_aead(Cipher, Key, IV, InText, AAD, EncFlag :: true) -> Result
                              when
                                  Cipher :: cipher_aead(),
                                  Key :: iodata(),
                                  IV :: iodata(),
                                  InText :: iodata(),
                                  AAD :: iodata(),
                                  Result :: EncryptResult,
                                  EncryptResult :: {OutCryptoText, OutTag},
                                  OutCryptoText :: binary(),
                                  OutTag :: binary().

Equivalent to crypto_one_time_aead/7.

Link to this function

crypto_one_time_aead(Cipher, Key, IV, InText, AAD, TagOrTagLength, EncFlag)

View Source (since OTP 22.0)
-spec crypto_one_time_aead(Cipher, Key, IV, InText, AAD, TagOrTagLength, EncFlag) -> Result
                              when
                                  Cipher :: cipher_aead(),
                                  Key :: iodata(),
                                  IV :: iodata(),
                                  InText :: iodata(),
                                  AAD :: iodata(),
                                  TagOrTagLength :: EncryptTagLength | DecryptTag,
                                  EncryptTagLength :: non_neg_integer(),
                                  DecryptTag :: iodata(),
                                  EncFlag :: boolean(),
                                  Result :: EncryptResult | DecryptResult,
                                  EncryptResult :: {OutCryptoText, OutTag},
                                  DecryptResult :: OutPlainText | error,
                                  OutCryptoText :: binary(),
                                  OutTag :: binary(),
                                  OutPlainText :: binary().

Do a complete encrypt or decrypt with an AEAD cipher of the full text.

For encryption, set the EncryptFlag to true and set the TagOrTagLength to the wanted size (in bytes) of the tag, that is, the tag length. If the default length is wanted, the crypto_one_time_aead/6 form may be used.

For decryption, set the EncryptFlag to false and put the tag to be checked in the argument TagOrTagLength.

Additional Authentication Data (AAD) is plaintext data that will not be encrypted, but will be covered by authenticity protection. It should be provided through the AAD argument, but can be an empty binary as well (<<>>) if not needed. In that case, a plain AE (Authenticated Encryption) is performed instead of AEAD (Authenticated Encryption with Associated Data). This function only supports ciphers that can be used both with and without AAD.

Uses the 3-tuple style for error handling.

See examples in the User's Guide.

Link to this function

crypto_update(State, Data)

View Source (since OTP 22.0)
-spec crypto_update(State, Data) -> Result
                       when State :: crypto_state(), Data :: iodata(), Result :: binary().

Add data to a streaming encryption or decryption operation.

If the part is less than a number of full blocks, only the full blocks (possibly none) are encrypted or decrypted and the remaining bytes are saved to the next crypto_update operation. The State should be created with crypto_init/3 or crypto_init/4.

Uses the 3-tuple style for error handling.

See examples in the User's Guide.

Hash API

Link to this function

hash(Type, Data)

View Source (since OTP R15B02)
-spec hash(Type, Data) -> Digest when Type :: hash_algorithm(), Data :: iodata(), Digest :: binary().

Compute a message digest.

Argument Type is the digest type and argument Data is the full message.

Uses the 3-tuple style for error handling.

Link to this function

hash_final(State)

View Source (since OTP R15B02)
-spec hash_final(State) -> Digest when State :: hash_state(), Digest :: binary().

Finalize a streaming hash calculation.

Argument State as returned from the last call to hash_update. The size of Digest is determined by the type of hash function used to generate it.

Uses the 3-tuple style for error handling.

Link to this function

hash_init(Type)

View Source (since OTP R15B02)
-spec hash_init(Type) -> State when Type :: hash_algorithm(), State :: hash_state().

Initialize the state for a streaming hash digest calculation.

Argument Type determines which digest to use. The returned state should be used as argument to hash_update/2.

Uses the 3-tuple style for error handling.

Link to this function

hash_update(State, Data)

View Source (since OTP R15B02)
-spec hash_update(State, Data) -> NewState
                     when State :: hash_state(), NewState :: hash_state(), Data :: iodata().

Add data to a streaming digest calculation.

Update the digest using the given Data of any length.

Argument State must have been generated by hash_init or a previous call to this function.

Returns NewState that must be passed into the next call to hash_update/2 or hash_final/1.

Uses the 3-tuple style for error handling.

Link to this function

hash_xof(Type, Data, Length)

View Source (since OTP 26.0)
-spec hash_xof(Type, Data, Length) -> Digest
                  when
                      Type :: hash_xof_algorithm(),
                      Data :: iodata(),
                      Length :: non_neg_integer(),
                      Digest :: binary().

Compute a message digest for an xof_algorithm.

Argument Type is the type of digest, Data is the full text and Length is the digest length in bits.

Uses the 3-tuple style for error handling.

May raise exception error:notsup in case the chosen Type is not supported by the underlying libcrypto implementation.

MAC API

Link to this function

mac(Type, Key, Data)

View Source (since OTP 22.1)
-spec mac(Type :: poly1305, Key, Data) -> Mac when Key :: iodata(), Data :: iodata(), Mac :: binary().

Compute a poly1305 MAC (Message Authentication Code).

Same as mac(Type, undefined, Key, Data).

Uses the 3-tuple style for error handling.

Link to this function

mac(Type, SubType, Key, Data)

View Source (since OTP 22.1)
-spec mac(Type, SubType, Key, Data) -> Mac
             when
                 Type :: hmac | cmac | poly1305,
                 SubType :: hmac_hash_algorithm() | cmac_cipher_algorithm() | undefined,
                 Key :: iodata(),
                 Data :: iodata(),
                 Mac :: binary().

Compute a MAC (Message Authentication Code).

Argument Type is the type of MAC and Data is the full message.

SubType depends on the MAC Type:

  • For hmac it is a hash algorithm, see Algorithm Details in the User's Guide.
  • For cmac it is a cipher suitable for cmac, see Algorithm Details in the User's Guide.
  • For poly1305 it should be set to undefined or the mac/2 function could be used instead, see Algorithm Details in the User's Guide.

Key is the authentication key with a length according to the Type and SubType. The key length could be found with the hash_info/1 (hmac) for and cipher_info/1 (cmac) functions. For poly1305 the key length is 32 bytes. Note that the cryptographic quality of the key is not checked.

The Mac result will have a default length depending on the Type and SubType. To set a shorter length, use macN/4 or macN/5 instead. The default length is documented in Algorithm Details in the User's Guide.

Uses the 3-tuple style for error handling.

Link to this function

mac_final(State)

View Source (since OTP 22.1)
-spec mac_final(State) -> Mac when State :: mac_state(), Mac :: binary().

Finalize a streaming MAC operation.

Argument State is the state as returned by the last call to mac_update/2.

The Mac result will have a default length depending on the Type and SubType in the mac_init/2,3 call. To set a shorter length, use mac_finalN/2 instead. The default length is documented in Algorithm Details in the User's Guide.

Uses the 3-tuple style for error handling.

Link to this function

mac_finalN(State, MacLength)

View Source (since OTP 22.1)
-spec mac_finalN(State, MacLength) -> Mac
                    when State :: mac_state(), MacLength :: pos_integer(), Mac :: binary().

Finalize a MAC operation with a custom length.

Argument State is the state as returned by the last call to mac_update/2.

Mac will be a binary with at most MacLength bytes. Note that if MacLength is greater than the actual number of bytes returned from the underlying hash, the returned hash will have that shorter length instead.

The max MacLength is documented in Algorithm Details in the User's Guide.

Uses the 3-tuple style for error handling.

Link to this function

mac_init(Type, Key)

View Source (since OTP 22.1)
-spec mac_init(Type :: poly1305, Key) -> State when Key :: iodata(), State :: mac_state().

Initialize a state for streaming poly1305 MAC calculation.

Same as mac_init(Type, undefined, Key).

Uses the 3-tuple style for error handling.

Link to this function

mac_init(Type, SubType, Key)

View Source (since OTP 22.1)
-spec mac_init(Type, SubType, Key) -> State
                  when
                      Type :: hmac | cmac | poly1305,
                      SubType :: hmac_hash_algorithm() | cmac_cipher_algorithm() | undefined,
                      Key :: iodata(),
                      State :: mac_state().

Initialize the state for streaming MAC calculation.

Type determines which mac algorithm to use in the MAC operation.

SubType depends on the MAC Type:

  • For hmac it is a hash algorithm, see Algorithm Details in the User's Guide.
  • For cmac it is a cipher suitable for cmac, see Algorithm Details in the User's Guide.
  • For poly1305 it should be set to undefined or the mac/2 function could be used instead, see Algorithm Details in the User's Guide.

Key is the authentication key with a length according to the Type and SubType. The key length could be found with the hash_info/1 (hmac) for and cipher_info/1 (cmac) functions. For poly1305 the key length is 32 bytes. Note that the cryptographic quality of the key is not checked.

The returned State should be used in one or more subsequent calls to mac_update/2. The MAC value is finally returned by calling mac_final/1 or mac_finalN/2.

Uses the 3-tuple style for error handling.

See examples in the User's Guide.

Link to this function

mac_update(State0, Data)

View Source (since OTP 22.1)
-spec mac_update(State0, Data) -> State
                    when Data :: iodata(), State0 :: mac_state(), State :: mac_state().

Add data to a streaming MAC calculation.

Update the MAC represented by State0 using the given Data which could be of any length.

The State0 is the State value originally from a MAC init function, that is mac_init/2, mac_init/3 or the last call to mac_update/2. The value State0 is returned unchanged by the function as a reference to a mutated internal state. Hence, it is not possible to branch off a data stream by reusing old states.

Uses the 3-tuple style for error handling.

Link to this function

macN(Type, Key, Data, MacLength)

View Source (since OTP 22.1)
-spec macN(Type :: poly1305, Key, Data, MacLength) -> Mac
              when Key :: iodata(), Data :: iodata(), Mac :: binary(), MacLength :: pos_integer().

Compute a poly1305 MAC (Message Authentication Code) with a limited length.

Same as macN(Type, undefined, Key, Data, MacLength).

Uses the 3-tuple style for error handling.

Link to this function

macN(Type, SubType, Key, Data, MacLength)

View Source (since OTP 22.1)
-spec macN(Type, SubType, Key, Data, MacLength) -> Mac
              when
                  Type :: hmac | cmac | poly1305,
                  SubType :: hmac_hash_algorithm() | cmac_cipher_algorithm() | undefined,
                  Key :: iodata(),
                  Data :: iodata(),
                  Mac :: binary(),
                  MacLength :: pos_integer().

Compute a MAC (Message Authentication Code) with a limited length.

Works like mac/3 and mac/4 but MacLength will limit the size of the resultant Mac to at most MacLength bytes. Note that if MacLength is greater than the actual number of bytes returned from the underlying hash, the returned hash will have that shorter length instead.

The max MacLength is documented in Algorithm Details in the User's Guide.

Key API

Link to this function

compute_key(Type, OthersPublicKey, MyPrivateKey, Params)

View Source (since OTP R16B01)
-spec compute_key(Type, OthersPublicKey, MyPrivateKey, Params) -> SharedSecret
                     when
                         Type :: dh | ecdh | eddh | srp,
                         SharedSecret :: binary(),
                         OthersPublicKey :: dh_public() | ecdh_public() | srp_public(),
                         MyPrivateKey :: dh_private() | ecdh_private() | {srp_public(), srp_private()},
                         Params :: dh_params() | ecdh_params() | srp_comp_params().

Compute the shared secret from the private key and the other party's public key.

See also public_key:compute_key/2.

Uses the 3-tuple style for error handling.

Link to this function

generate_key(Type, Params)

View Source (since OTP R16B01)
-spec generate_key(Type, Params) -> {PublicKey, PrivKeyOut}
                      when
                          Type :: dh | ecdh | eddh | eddsa | rsa | srp,
                          PublicKey :: dh_public() | ecdh_public() | rsa_public() | srp_public(),
                          PrivKeyOut ::
                              dh_private() |
                              ecdh_private() |
                              rsa_private() |
                              {srp_public(), srp_private()},
                          Params ::
                              dh_params() |
                              ecdh_params() |
                              eddsa_params() |
                              rsa_params() |
                              srp_gen_params().

Equivalent to generate_key/3.

Link to this function

generate_key(Type, Params, PrivKeyIn)

View Source (since OTP R16B01)
-spec generate_key(Type, Params, PrivKeyIn) -> {PublicKey, PrivKeyOut}
                      when
                          Type :: dh | ecdh | eddh | eddsa | rsa | srp,
                          PublicKey :: dh_public() | ecdh_public() | rsa_public() | srp_public(),
                          PrivKeyIn ::
                              undefined |
                              dh_private() |
                              ecdh_private() |
                              rsa_private() |
                              {srp_public(), srp_private()},
                          PrivKeyOut ::
                              dh_private() |
                              ecdh_private() |
                              rsa_private() |
                              {srp_public(), srp_private()},
                          Params ::
                              dh_params() |
                              ecdh_params() |
                              eddsa_params() |
                              rsa_params() |
                              srp_comp_params().

Generate a public key.

See also public_key:generate_key/1.

Uses the 3-tuple style for error handling.

Note

If the linked version of cryptolib is OpenSSL 3.0

  • and the Type is dh (diffie-hellman)
  • and the parameter P (in dh_params/0) is one of the MODP groups (see RFC 3526)
  • and the optional PrivateKeyBitLength parameter (in dh_params/0) is present,

then the optional key length parameter must be at least 224, 256, 302, 352 and 400 for group sizes of 2048, 3072, 4096, 6144 and 8192, respectively.

Sign/Verify API

Link to this function

sign(Algorithm, DigestType, Msg, Key)

View Source (since OTP R16B01)
-spec sign(Algorithm, DigestType, Msg, Key) -> Signature
              when
                  Algorithm :: pk_sign_verify_algs(),
                  DigestType :: rsa_digest_type() | dss_digest_type() | ecdsa_digest_type() | none,
                  Msg :: iodata() | {digest, iodata()},
                  Key ::
                      rsa_private() |
                      dss_private() |
                      [ecdsa_private() | ecdsa_params()] |
                      [eddsa_private() | eddsa_params()] |
                      engine_key_ref(),
                  Signature :: binary().

Equivalent to sign/5.

Link to this function

sign(Algorithm, DigestType, Msg, Key, Options)

View Source (since OTP 20.1)
-spec sign(Algorithm, DigestType, Msg, Key, Options) -> Signature
              when
                  Algorithm :: pk_sign_verify_algs(),
                  DigestType :: rsa_digest_type() | dss_digest_type() | ecdsa_digest_type() | none,
                  Msg :: iodata() | {digest, iodata()},
                  Key ::
                      rsa_private() |
                      dss_private() |
                      [ecdsa_private() | ecdsa_params()] |
                      [eddsa_private() | eddsa_params()] |
                      engine_key_ref(),
                  Options :: pk_sign_verify_opts(),
                  Signature :: binary().

Create a digital signature.

The msg is either the binary "cleartext" data to be signed or it is the hashed value of "cleartext" i.e. the digest (plaintext).

Algorithm dss can only be used together with digest type sha.

Uses the 3-tuple style for error handling.

See also public_key:sign/3.

Link to this function

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

View Source (since OTP R16B01)
-spec verify(Algorithm, DigestType, Msg, Signature, Key) -> Result
                when
                    Algorithm :: pk_sign_verify_algs(),
                    DigestType :: rsa_digest_type() | dss_digest_type() | ecdsa_digest_type() | none,
                    Msg :: iodata() | {digest, iodata()},
                    Signature :: binary(),
                    Key ::
                        rsa_public() |
                        dss_public() |
                        [ecdsa_public() | ecdsa_params()] |
                        [eddsa_public() | eddsa_params()] |
                        engine_key_ref(),
                    Result :: boolean().

Equivalent to verify/6.

Link to this function

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

View Source (since OTP 20.1)
-spec verify(Algorithm, DigestType, Msg, Signature, Key, Options) -> Result
                when
                    Algorithm :: pk_sign_verify_algs(),
                    DigestType :: rsa_digest_type() | dss_digest_type() | ecdsa_digest_type() | none,
                    Msg :: iodata() | {digest, iodata()},
                    Signature :: binary(),
                    Key ::
                        rsa_public() |
                        dss_public() |
                        [ecdsa_public() | ecdsa_params()] |
                        [eddsa_public() | eddsa_params()] |
                        engine_key_ref(),
                    Options :: pk_sign_verify_opts(),
                    Result :: boolean().

Verify a digital signature.

The msg is either the binary "cleartext" data to be signed or it is the hashed value of "cleartext" i.e. the digest (plaintext).

Algorithm dss can only be used together with digest type sha.

Uses the 3-tuple style for error handling.

See also public_key:verify/4.

Random API

Link to this function

rand_seed()

View Source (since OTP 20.0)
-spec rand_seed() -> rand:state().

Create a state object for random number generation, in order to generate cryptographically strong random numbers (based on OpenSSL's BN_rand_range).

Saves the state in the process dictionary before returning it as well. See also rand:seed/1 and rand_seed_s/0.

When using the state object from this function the rand functions using it may raise exception error:low_entropy in case the random generator failed due to lack of secure "randomness".

Example

_ = crypto:rand_seed(),
_IntegerValue = rand:uniform(42), % [1; 42]
_FloatValue = rand:uniform().     % [0.0; 1.0[
Link to this function

rand_seed(Seed)

View Source (since OTP 17.0)
-spec rand_seed(binary()) -> ok.

Set the seed for PRNG to the given binary.

This calls the RAND_seed function from openssl. Only use this if the system you are running on does not have enough "randomness" built in. Normally this is when strong_rand_bytes/1 raises error:low_entropy.

Link to this function

rand_seed_alg(Alg)

View Source (since OTP 21.0)
-spec rand_seed_alg(Alg :: atom()) -> {rand:alg_handler(), atom() | rand_cache_seed()}.

Create a state object for random number generation, in order to generate cryptographically strong random numbers.

Saves the state in the process dictionary before returning it as well. See also rand:seed/1 and rand_seed_alg_s/1.

When using the state object from this function the rand functions using it may raise exception error:low_entropy in case the random generator failed due to lack of secure "randomness".

Example

_ = crypto:rand_seed_alg(crypto_cache),
_IntegerValue = rand:uniform(42), % [1; 42]
_FloatValue = rand:uniform().     % [0.0; 1.0[
Link to this function

rand_seed_alg(Alg, Seed)

View Source (since OTP-22.0)
-spec rand_seed_alg(Alg :: atom(), Seed :: term()) -> {rand:alg_handler(), atom() | rand_cache_seed()}.

Creates a state object for random number generation, in order to generate cryptographically unpredictable random numbers.

Saves the state in the process dictionary before returning it as well. See also rand_seed_alg_s/2.

Example

_ = crypto:rand_seed_alg(crypto_aes, "my seed"),
IntegerValue = rand:uniform(42), % [1; 42]
FloatValue = rand:uniform(),     % [0.0; 1.0[
_ = crypto:rand_seed_alg(crypto_aes, "my seed"),
IntegerValue = rand:uniform(42), % Same values
FloatValue = rand:uniform().     % again
Link to this function

rand_seed_alg_s(Alg)

View Source (since OTP 21.0)
-spec rand_seed_alg_s(Alg :: atom()) -> {rand:alg_handler(), atom() | rand_cache_seed()}.

Create a state object for random number generation, in order to generate cryptographically strongly random numbers.

See also rand:seed_s/1.

If Alg is crypto this function behaves exactly like rand_seed_s/0.

If Alg is crypto_cache this function fetches random data with OpenSSL's RAND_bytes and caches it for speed using an internal word size of 56 bits that makes calculations fast on 64 bit machines.

When using the state object from this function the rand functions using it may raise exception error:low_entropy in case the random generator failed due to lack of secure "randomness".

The cache size can be changed from its default value using the crypto app's configuration parameter rand_cache_size.

Note

The state returned from this function cannot be used to get a reproducible random sequence as from the other rand functions, since reproducibility does not match cryptographically safe.

In fact since random data is cached some numbers may get reproduced if you try, but this is unpredictable.

The only supported usage is to generate one distinct random sequence from this start state.

Link to this function

rand_seed_alg_s(Alg, Seed)

View Source (since OTP 22.0)
-spec rand_seed_alg_s(Alg :: atom(), Seed :: term()) -> {rand:alg_handler(), atom() | rand_cache_seed()}.

Create a state object for random number generation, in order to generate cryptographically unpredictable random numbers.

See also rand_seed_alg/1.

To get a long period the Xoroshiro928 generator from the rand module is used as a counter (with period 2^928 - 1) and the generator states are scrambled through AES to create 58-bit pseudo random values.

The result should be statistically completely unpredictable random values, since the scrambling is cryptographically strong and the period is ridiculously long. But the generated numbers are not to be regarded as cryptographically strong since there is no re-keying schedule.

  • If you need cryptographically strong random numbers use rand_seed_alg_s/1 with Alg =:= crypto or Alg =:= crypto_cache.
  • If you need to be able to repeat the sequence use this function.
  • If you do not need the statistical quality of this function, there are faster algorithms in the rand module.

Thanks to the used generator the state object supports the rand:jump/0,1 function with distance 2^512.

Numbers are generated in batches and cached for speed reasons. The cache size can be changed from its default value using the crypto app's configuration parameter rand_cache_size.

Link to this function

rand_seed_s()

View Source (since OTP 20.0)
-spec rand_seed_s() -> rand:state().

Create a state object for random number generation, in order to generate cryptographically strongly random numbers (based on OpenSSL's BN_rand_range). See also rand:seed_s/1.

When using the state object from this function the rand functions using it may raise exception error:low_entropy in case the random generator failed due to lack of secure "randomness".

Note

The state returned from this function cannot be used to get a reproducible random sequence as from the other rand functions, since reproducibility does not match cryptographically safe.

The only supported usage is to generate one distinct random sequence from this start state.

This function is deprecated. crypto:rand_uniform/2 is deprecated; use rand:uniform/1 instead.
-spec rand_uniform(crypto_integer(), crypto_integer()) -> crypto_integer().

Generate a random integer number.

The interval is From =< N < To. Uses the crypto library pseudo-random number generator. To must be larger than From.

Link to this function

strong_rand_bytes(N)

View Source (since OTP R14B03)
-spec strong_rand_bytes(N :: non_neg_integer()) -> binary().

Generate bytes with randomly uniform values 0..255.

Returns the result in a binary with N bytes.

Uses a cryptographically secure PRNG seeded and periodically mixed with operating system provided entropy. By default this is the RAND_bytes method from OpenSSL.

May raise exception error:low_entropy in case the random generator failed due to lack of secure "randomness".

Utility Functions

Link to this function

bytes_to_integer(Bin)

View Source (since OTP R16B01)
-spec bytes_to_integer(binary()) -> integer().

Convert binary representation, of an integer, to an Erlang integer.

Link to this function

cipher_info(Type)

View Source (since OTP 22.0)
-spec cipher_info(Type) -> Result
                     when
                         Type :: cipher(),
                         Result ::
                             #{key_length := integer(),
                               iv_length := integer(),
                               block_size := integer(),
                               mode := CipherModes,
                               type := undefined | integer(),
                               prop_aead := boolean()},
                         CipherModes ::
                             undefined | cbc_mode | ccm_mode | cfb_mode | ctr_mode | ecb_mode |
                             gcm_mode | ige_mode | ocb_mode | ofb_mode | wrap_mode | xts_mode.

Get information about a cipher algorithm.

Returns a map with information about block size, key length, IV length, aead support and possibly other properties of the cipher algorithm in question.

Note

The ciphers aes_cbc, aes_cfb8, aes_cfb128, aes_ctr, aes_ecb, aes_gcm and aes_ccm has no keylength in the Type as opposed to for example aes_128_ctr. They adapt to the length of the key provided in the encrypt and decrypt function. Therefore it is impossible to return a valid keylength in the map.

Always use a Type with an explicit key length,

For a list of supported cipher algorithms, see supports(ciphers).

Link to this function

ec_curve(CurveName)

View Source (since OTP 17.0)
-spec ec_curve(CurveName) -> ExplicitCurve
                  when CurveName :: ec_named_curve(), ExplicitCurve :: ec_explicit_curve().

Return the defining parameters of a elliptic curve.

Link to this function

ec_curves()

View Source (since OTP 17.0)
-spec ec_curves() -> [EllipticCurve]
                   when EllipticCurve :: ec_named_curve() | edwards_curve_dh() | edwards_curve_ed().

Return all supported named elliptic curves.

Link to this function

enable_fips_mode(Enable)

View Source (since OTP 21.1)
-spec enable_fips_mode(Enable) -> Result when Enable :: boolean(), Result :: boolean().

Enable or disable FIPs mode.

Argument Enable should be true to enable and false to disable FIPS mode. Returns true if the operation was successful or false otherwise.

Note that to enable FIPS mode successfully, OTP must be built with the configure option --enable-fips, and the underlying libcrypto must also support FIPS.

See also info_fips/0.

-spec exor(iodata(), iodata()) -> binary().

Perform bit-wise XOR (exclusive or) on the data supplied.

The two byte sequences mus be of equal length.

Link to this function

hash_equals(BinA, BinB)

View Source (since OTP 25.0)
-spec hash_equals(BinA, BinB) -> Result when BinA :: binary(), BinB :: binary(), Result :: boolean().

Compare two binaries in constant time, such as results of HMAC computations.

Returns true if the binaries are identical, false if they are of the same length but not identical. The function raises an error:badarg exception if the binaries are of different size.

Link to this function

hash_info(Type)

View Source (since OTP 22.0)
-spec hash_info(Type) -> Result
                   when
                       Type :: hash_algorithm(),
                       Result :: #{size := integer(), block_size := integer(), type := integer()}.

Get information about a hash algorithm.

Returns a map with information about block_size, size and possibly other properties of the hash algorithm in question.

For a list of supported hash algorithms, see supports(hashs).

-spec info() ->
              #{compile_type := normal | debug | valgrind | asan,
                cryptolib_version_compiled => string() | undefined,
                cryptolib_version_linked := string(),
                link_type := dynamic | static,
                otp_crypto_version := string()}.

Get information about crypto and the OpenSSL backend.

Returns a map with information about the compilation and linking of crypto.

Example:

1> crypto:info().
#{compile_type => normal,
  cryptolib_version_compiled => "OpenSSL 3.0.0 7 sep 2021",
  cryptolib_version_linked => "OpenSSL 3.0.0 7 sep 2021",
  link_type => dynamic,
  otp_crypto_version => "5.0.2"}
2>

More association types than documented may be present in the map.

Link to this function

info_fips()

View Source (since OTP 20.0)
-spec info_fips() -> not_supported | not_enabled | enabled.

Get information about the operating status of FIPS.

Returns the FIPS operating status of crypto and the underlying libcrypto library. If crypto was built with FIPS support this can be either enabled (when running in FIPS mode) or not_enabled. For other builds this value is always not_supported.

See enable_fips_mode/1 about how to enable FIPS mode.

Warning

In FIPS mode all non-FIPS compliant algorithms are disabled and raise exception error:notsup. Check supports(ciphers) that in FIPS mode returns the restricted list of available algorithms.

-spec info_lib() -> [{Name, VerNum, VerStr}]
                  when Name :: binary(), VerNum :: integer(), VerStr :: binary().

Get the name and version of the libraries used by crypto.

Name is the name of the library. VerNum is the numeric version according to the library's own versioning scheme. VerStr contains a text variant of the version.

> info_lib().
[{<<"OpenSSL">>,269484095,<<"OpenSSL 1.1.0c  10 Nov 2016"">>}]

Note

From OTP R16 the numeric version represents the version of the OpenSSL header files (openssl/opensslv.h) used when crypto was compiled. The text variant represents the libcrypto library used at runtime. In earlier OTP versions both numeric and text was taken from the library.

Link to this function

mod_pow(N, P, M)

View Source (since OTP R16B01)
-spec mod_pow(N, P, M) -> Result
                 when
                     N :: binary() | integer(),
                     P :: binary() | integer(),
                     M :: binary() | integer(),
                     Result :: binary() | error.

Compute the function N^P mod M.

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

Use application:start(crypto) instead.

Warning

This function does not work if FIPS mode is to be enabled. FIPS mode will be disabled even if configuration parameter fips_mode is set to true. Use application:start(crypto) instead.

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

Use application:stop(crypto) instead.

Link to this function

supports(Type)

View Source (since OTP 22.0)
-spec supports(Type) -> Support
                  when
                      Type :: hashs | ciphers | public_keys | macs | curves | rsa_opts,
                      Support :: Hashs | Ciphers | PKs | Macs | Curves | RSAopts,
                      Hashs ::
                          [sha1() |
                           sha2() |
                           sha3() |
                           sha3_xof() |
                           blake2() |
                           ripemd160 |
                           compatibility_only_hash()],
                      Ciphers :: [cipher()],
                      PKs :: [rsa | dss | ecdsa | dh | ecdh | eddh | ec_gf2m],
                      Macs :: [hmac | cmac | poly1305],
                      Curves :: [ec_named_curve() | edwards_curve_dh() | edwards_curve_ed()],
                      RSAopts :: [rsa_sign_verify_opt() | rsa_opt()].

Get which crypto algorithms that are supported by the underlying libcrypto library.

See hash_info/1 and cipher_info/1 for information about the hash and cipher algorithms.

Engine API

Link to this function

engine_add(Engine)

View Source (since OTP 21.0.6)
-spec engine_add(Engine) -> Result when Engine :: engine_ref(), Result :: ok | {error, Reason :: term()}.

Add the engine to OpenSSL's internal list.

The function raises a error:badarg if the parameters are in wrong format. It may also raise the exception error:notsup in case there is no engine support in the underlying OpenSSL implementation.

Link to this function

engine_by_id(EngineId)

View Source (since OTP 21.0.6)
-spec engine_by_id(EngineId) -> Result
                      when
                          EngineId :: unicode:chardata(),
                          Result :: {ok, Engine :: engine_ref()} | {error, Reason :: term()}.

Get a reference to an already loaded engine with EngineId. An error tuple is returned if the engine can't be unloaded.

The function raises a error:badarg if the parameter is in wrong format. It may also raise the exception error:notsup in case there is no engine support in the underlying OpenSSL implementation.

See also the chapter Engine Load in the User's Guide.

Link to this function

engine_ctrl_cmd_string(Engine, CmdName, CmdArg)

View Source (since OTP 20.2)
-spec engine_ctrl_cmd_string(Engine, CmdName, CmdArg) -> Result
                                when
                                    Engine :: term(),
                                    CmdName :: unicode:chardata(),
                                    CmdArg :: unicode:chardata(),
                                    Result :: ok | {error, Reason :: term()}.

Send ctrl commands to an OpenSSL engine.

This function is the same as calling engine_ctrl_cmd_string/4 with Optional set to false.

The function raises a error:badarg if the parameters are in wrong format. It may also raise the exception error:notsup in case there is no engine support in the underlying OpenSSL implementation.

Link to this function

engine_ctrl_cmd_string(Engine, CmdName, CmdArg, Optional)

View Source (since OTP 20.2)
-spec engine_ctrl_cmd_string(Engine, CmdName, CmdArg, Optional) -> Result
                                when
                                    Engine :: term(),
                                    CmdName :: unicode:chardata(),
                                    CmdArg :: unicode:chardata(),
                                    Optional :: boolean(),
                                    Result :: ok | {error, Reason :: term()}.

Send ctrl commands to an OpenSSL engine.

Optional is a boolean argument that can relax the semantics of the function. If set to true it will only return failure if the ENGINE supported the given command name but failed while executing it, if the ENGINE doesn't support the command name it will simply return success without doing anything. In this case we assume the user is only supplying commands specific to the given ENGINE so we set this to false.

The function raises a error:badarg if the parameters are in wrong format. It may also raise the exception error:notsup in case there is no engine support in the underlying OpenSSL implementation.

Link to this function

engine_get_all_methods()

View Source (since OTP 20.2)
-spec engine_get_all_methods() -> Result when Result :: [engine_method_type()].

Return a list of all possible engine methods.

May raise exception error:notsup in case there is no engine support in the underlying OpenSSL implementation.

See also the chapter Engine Load in the User's Guide.

Link to this function

engine_get_id(Engine)

View Source (since OTP 21.0.6)
-spec engine_get_id(Engine) -> EngineId when Engine :: engine_ref(), EngineId :: unicode:chardata().

Return the ID for the engine, or an empty binary if there is no id set.

The function raises a error:badarg if the parameters are in wrong format. It may also raise the exception error:notsup in case there is no engine support in the underlying OpenSSL implementation.

Link to this function

engine_get_name(Engine)

View Source (since OTP 21.0.6)
-spec engine_get_name(Engine) -> EngineName
                         when Engine :: engine_ref(), EngineName :: unicode:chardata().

Return the name (eg a description) for the engine, or an empty binary if there is no name set.

The function raises a error:badarg if the parameters are in wrong format. It may also raise the exception error:notsup in case there is no engine support in the underlying OpenSSL implementation.

Link to this function

engine_list()

View Source (since OTP 20.2)
-spec engine_list() -> Result when Result :: [EngineId :: unicode:chardata()].

List the id's of all engines in OpenSSL's internal list.

It may also raise the exception error:notsup in case there is no engine support in the underlying OpenSSL implementation.

See also the chapter Engine Load in the User's Guide.

May raise exception error:notsup in case engine functionality is not supported by the underlying OpenSSL implementation.

Link to this function

engine_load(EngineId, PreCmds, PostCmds)

View Source (since OTP 20.2)
-spec engine_load(EngineId, PreCmds, PostCmds) -> Result
                     when
                         EngineId :: unicode:chardata(),
                         PreCmds :: [engine_cmnd()],
                         PostCmds :: [engine_cmnd()],
                         Result :: {ok, Engine :: engine_ref()} | {error, Reason :: term()}.

Load an OpenSSL engine.

Loads the OpenSSL engine given by EngineId if it is available and intialize it. Returns ok and an engine handle, or if the engine can't be loaded an error tuple is returned.

The function raises a error:badarg if the parameters are in wrong format. It may also raise the exception error:notsup in case there is no engine support in the underlying OpenSSL implementation.

See also the chapter Engine Load in the User's Guide.

Link to this function

engine_register(Engine, EngineMethods)

View Source (since OTP 25.1)
-spec engine_register(Engine, EngineMethods) -> Result
                         when
                             Engine :: engine_ref(),
                             EngineMethods :: [engine_method_type()],
                             Result :: ok | {error, Reason :: term()}.

Register engine to handle some type of methods, for example engine_method_digests.

The function raises a error:badarg if the parameters are in wrong format. It may also raise the exception error:notsup in case there is no engine support in the underlying OpenSSL implementation.

Link to this function

engine_remove(Engine)

View Source (since OTP 21.0.6)
-spec engine_remove(Engine) -> Result
                       when Engine :: engine_ref(), Result :: ok | {error, Reason :: term()}.

Remove the engine from OpenSSL's internal list.

The function raises a error:badarg if the parameters are in wrong format. It may also raise the exception error:notsup in case there is no engine support in the underlying OpenSSL implementation.

Link to this function

engine_unload(Engine)

View Source (since OTP 20.2)
-spec engine_unload(Engine) -> Result
                       when Engine :: engine_ref(), Result :: ok | {error, Reason :: term()}.

Unload an OpenSSL engine.

Unloads the OpenSSL engine given by Engine. An error tuple is returned if the engine can't be unloaded.

The function raises a error:badarg if the parameter is in wrong format. It may also raise the exception error:notsup in case there is no engine support in the underlying OpenSSL implementation.

See also the chapter Engine Load in the User's Guide.

Link to this function

engine_unregister(Engine, EngineMethods)

View Source (since OTP 25.1)
-spec engine_unregister(Engine, EngineMethods) -> Result
                           when
                               Engine :: engine_ref(),
                               EngineMethods :: [engine_method_type()],
                               Result :: ok | {error, Reason :: term()}.

Unregister engine so it don't handle some type of methods.

The function raises a error:badarg if the parameters are in wrong format. It may also raise the exception error:notsup in case there is no engine support in the underlying OpenSSL implementation.

Link to this function

ensure_engine_loaded(EngineId, LibPath)

View Source (since OTP 21.0.6)
-spec ensure_engine_loaded(EngineId, LibPath) -> Result
                              when
                                  EngineId :: unicode:chardata(),
                                  LibPath :: unicode:chardata(),
                                  Result :: {ok, Engine :: engine_ref()} | {error, Reason :: term()}.

Load a dynamic engine if not already done.

Loada the engine given by EngineId and the path to the dynamic library implementing the engine. An error tuple is returned if the engine can't be loaded.

This function differs from the normal engine_load in the sense that it also add the engine id to OpenSSL's internal engine list. The difference between the first call and the following is that the first loads the engine with the dynamical engine and the following calls fetch it from the OpenSSL's engine list. All references that is returned are equal.

Use engine_unload/1 function to remove the references. But remember that engine_unload/1 just removes the references to the engine and not the tag in OpenSSL's engine list. That has to be done with the engine_remove/1 function when needed (just called once, from any of the references you got).

The function raises a error:badarg if the parameters are in wrong format. It may also raise the exception error:notsup in case there is no engine support in the underlying OpenSSL implementation.

See also the chapter Engine Load in the User's Guide.

Link to this function

pbkdf2_hmac(Digest, Pass, Salt, Iter, KeyLen)

View Source (since OTP 24.2)
-spec pbkdf2_hmac(Digest, Pass, Salt, Iter, KeyLen) -> Result
                     when
                         Digest :: sha | sha224 | sha256 | sha384 | sha512,
                         Pass :: binary(),
                         Salt :: binary(),
                         Iter :: pos_integer(),
                         KeyLen :: pos_integer(),
                         Result :: binary().

PKCS #5 PBKDF2 (Password-Based Key Derivation Function 2) in combination with HMAC.

Uses the 3-tuple style for error handling.

Link to this function

privkey_to_pubkey(Type, EnginePrivateKeyRef)

View Source (since OTP 20.2)
-spec privkey_to_pubkey(Type, EnginePrivateKeyRef) -> PublicKey
                           when
                               Type :: rsa | dss,
                               EnginePrivateKeyRef :: engine_key_ref(),
                               PublicKey :: rsa_public() | dss_public().

Fetch public key from a private key stored in an Engine.

The key must be of the type indicated by the Type parameter.

Legacy RSA Encryption API

Link to this function

private_decrypt(Algorithm, CipherText, PrivateKey, Options)

View Source (since OTP R16B01)
-spec private_decrypt(Algorithm, CipherText, PrivateKey, Options) -> PlainText
                         when
                             Algorithm :: pk_encrypt_decrypt_algs(),
                             CipherText :: binary(),
                             PrivateKey :: rsa_private() | engine_key_ref(),
                             Options :: pk_encrypt_decrypt_opts(),
                             PlainText :: binary().

Decrypt using a private key.

Decrypts the CipherText, encrypted with public_encrypt/4 (or equivalent function) using the PrivateKey, and returns the plaintext (message digest). This is a low level signature verification operation used for instance by older versions of the SSL protocol. See also public_key:decrypt_private/2,3

Uses the 3-tuple style for error handling.

Warning

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

Link to this function

private_encrypt(Algorithm, PlainText, PrivateKey, Options)

View Source (since OTP R16B01)
-spec private_encrypt(Algorithm, PlainText, PrivateKey, Options) -> CipherText
                         when
                             Algorithm :: pk_encrypt_decrypt_algs(),
                             PlainText :: binary(),
                             PrivateKey :: rsa_private() | engine_key_ref(),
                             Options :: pk_encrypt_decrypt_opts(),
                             CipherText :: binary().

Encrypt using a private key.

Encrypts the PlainText using the PrivateKey and returns the ciphertext. This is a low level signature operation used for instance by older versions of the SSL protocol. See also public_key:encrypt_private/2,3

Uses the 3-tuple style for error handling.

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. For digital signatures use of sign/4 together with verify/5 is the prefered solution.

Link to this function

public_decrypt(Algorithm, CipherText, PublicKey, Options)

View Source (since OTP R16B01)
-spec public_decrypt(Algorithm, CipherText, PublicKey, Options) -> PlainText
                        when
                            Algorithm :: pk_encrypt_decrypt_algs(),
                            CipherText :: binary(),
                            PublicKey :: rsa_public() | engine_key_ref(),
                            Options :: pk_encrypt_decrypt_opts(),
                            PlainText :: binary().

Decrypt using a public key.

Decrypts the CipherText, encrypted with private_encrypt/4(or equivalent function) using the PublicKey, and returns the plaintext (message digest). This is a low level signature verification operation used for instance by older versions of the SSL protocol. See also public_key:decrypt_public/2,3

Uses the 3-tuple style for error handling.

Warning

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

Link to this function

public_encrypt(Algorithm, PlainText, PublicKey, Options)

View Source (since OTP R16B01)
-spec public_encrypt(Algorithm, PlainText, PublicKey, Options) -> CipherText
                        when
                            Algorithm :: pk_encrypt_decrypt_algs(),
                            PlainText :: binary(),
                            PublicKey :: rsa_public() | engine_key_ref(),
                            Options :: pk_encrypt_decrypt_opts(),
                            CipherText :: binary().

Encrypt using a public key.

Encrypts the PlainText (message digest) using the PublicKey and returns the CipherText. This is a low level signature operation used for instance by older versions of the SSL protocol. See also public_key:encrypt_public/2,3

Uses the 3-tuple style for error handling.

Warning

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