Module
crypto
Module Summary
Crypto Functions
Description
This module provides a set of cryptographic functions.
- Hash functions
- MACs - Message Authentication Codes
-
- Hmac functions
-
Keyed-Hashing for Message Authentication [RFC 2104]
- Cmac functions
-
The AES-CMAC Algorithm [RFC 4493]
- POLY1305
-
ChaCha20 and Poly1305 for IETF Protocols [RFC 7539]
- Symmetric Ciphers
-
- DES, 3DES and AES
-
Block Cipher Techniques [NIST]
- Blowfish
-
Fast Software Encryption, Cambridge Security Workshop Proceedings (December 1993), Springer-Verlag, 1994, pp. 191-204.
- Chacha20
-
ChaCha20 and Poly1305 for IETF Protocols [RFC 7539]
- Chacha20_poly1305
-
ChaCha20 and Poly1305 for IETF Protocols [RFC 7539]
- Modes
-
- ECB, CBC, CFB, OFB and CTR
-
Recommendation for Block Cipher Modes of Operation: Methods and Techniques [NIST SP 800-38A]
- GCM
-
Recommendation for Block Cipher Modes of Operation: Galois/Counter Mode (GCM) and GMAC [NIST SP 800-38D]
- CCM
-
Recommendation for Block Cipher Modes of Operation: The CCM Mode for Authentication and Confidentiality [NIST SP 800-38C]
- Asymetric Ciphers - Public Key Techniques
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.
Data Types
Ciphers, new API
cipher() = cipher_no_iv() | cipher_iv() | cipher_aead()
cipher_no_iv() =
aes_128_ecb | aes_192_ecb | aes_256_ecb | blowfish_ecb |
des_ecb | rc4
cipher_iv() =
aes_128_cbc | aes_192_cbc | aes_256_cbc | aes_128_cfb128 |
aes_192_cfb128 | aes_256_cfb128 | aes_128_cfb8 |
aes_192_cfb8 | aes_256_cfb8 | aes_128_ctr | aes_192_ctr |
aes_256_ctr | aes_ige256 | blowfish_cbc | blowfish_cfb64 |
blowfish_ofb64 | chacha20 | des_ede3_cbc | des_ede3_cfb |
des_cbc | des_cfb | rc2_cbc
cipher_aead() =
aes_128_ccm | aes_192_ccm | aes_256_ccm | aes_128_gcm |
aes_192_gcm | aes_256_gcm | chacha20_poly1305
Ciphers known by the CRYPTO application when using the new API
.
Note that this list might be reduced if the underlying libcrypto does not support all of them.
crypto_opts() = boolean() | [crypto_opt()]
crypto_opt() = {encrypt, boolean()} | {padding, padding()}
Selects encryption ({encrypt,true}
) or decryption ({encrypt,false}
) in the New API
.
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.
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.
otp_padding() = zero | random
Erlang/OTP adds a either padding of zeroes or padding with random bytes.
Ciphers, old API
block_cipher_with_iv() =
cbc_cipher() | cfb_cipher() | blowfish_ofb64 | aes_ige256
block_cipher_without_iv() = ecb_cipher()
stream_cipher() = ctr_cipher() | chacha20 | rc4
aead_cipher() = aes_gcm | aes_ccm | chacha20_poly1305
cbc_cipher() =
aes_128_cbc | aes_192_cbc | aes_256_cbc | blowfish_cbc |
des_cbc | des_ede3_cbc | rc2_cbc |
retired_cbc_cipher_aliases()
cfb_cipher() =
aes_128_cfb128 | aes_192_cfb128 | aes_256_cfb128 |
aes_128_cfb8 | aes_192_cfb8 | aes_256_cfb8 | blowfish_cfb64 |
des_cfb | des_ede3_cfb |
retired_cfb_cipher_aliases()
ctr_cipher() =
aes_128_ctr | aes_192_ctr | aes_256_ctr |
retired_ctr_cipher_aliases()
ecb_cipher() =
aes_128_ecb | aes_192_ecb | aes_256_ecb | blowfish_ecb |
retired_ecb_cipher_aliases()
Ciphers known by the CRYPTO application when using the old API
.
Note that this list might be reduced if the underlying libcrypto does not support all of them.
retired_cbc_cipher_aliases() =
aes_cbc | aes_cbc128 | aes_cbc256 | des3_cbc | des_ede3
retired_cfb_cipher_aliases() =
aes_cfb8 | aes_cfb128 | des3_cbf | des3_cfb | des_ede3_cbf
retired_ctr_cipher_aliases() = aes_ctr
retired_ecb_cipher_aliases() = aes_ecb
Alternative, old names of ciphers known by the CRYPTO application when using the old API
. See Retired cipher names
for names to use instead to be prepared for an easy convertion to the new API
.
Note that this list might be reduced if the underlying libcrypto does not support all of them.
Digests and hash
hash_algorithm() =
sha1() |
sha2() |
sha3() |
blake2() |
ripemd160 |
compatibility_only_hash()
hmac_hash_algorithm() =
sha1() | sha2() | sha3() | compatibility_only_hash()
cmac_cipher_algorithm() =
aes_128_cbc | aes_192_cbc | aes_256_cbc | blowfish_cbc |
des_cbc | des_ede3_cbc | rc2_cbc | aes_128_cfb128 |
aes_192_cfb128 | aes_256_cfb128 | aes_128_cfb8 |
aes_192_cfb8 | aes_256_cfb8
sha1() = sha
sha2() = sha224 | sha256 | sha384 | sha512
sha3() = sha3_224 | sha3_256 | sha3_384 | sha3_512
blake2() = blake2b | blake2s
compatibility_only_hash() = md5 | md4
The compatibility_only_hash()
algorithms are recommended only for compatibility with existing applications.
Elliptic Curves
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
edwards_curve_dh() = x25519 | x448
edwards_curve_ed() = ed25519 | ed448
Note that some curves are disabled if FIPS is enabled.
ec_explicit_curve() =
{Field :: ec_field(),
Curve :: ec_curve(),
BasePoint :: binary(),
Order :: binary(),
CoFactor :: none | binary()}
ec_field() = ec_prime_field() | ec_characteristic_two_field()
ec_curve() =
{A :: binary(), B :: binary(), Seed :: none | binary()}
Parametric curve definition.
ec_prime_field() = {prime_field, Prime :: integer()}
ec_characteristic_two_field() =
{characteristic_two_field,
M :: integer(),
Basis :: ec_basis()}
ec_basis() =
{tpbasis, K :: integer() >= 0} |
{ppbasis,
K1 :: integer() >= 0,
K2 :: integer() >= 0,
K3 :: integer() >= 0} |
onbasis
Curve definition details.
Keys
For keylengths, iv-sizes and blocksizes see the User's Guide
.
A key for des3 is a list of three iolists
key_integer() = integer() | binary()
Always binary()
when used as return value
Public/Private Keys
rsa_public() = [key_integer()]
rsa_private() = [key_integer()]
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
.
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.
ecdsa_public() = key_integer()
ecdsa_private() = key_integer()
ecdsa_params() = ec_named_curve() | ec_explicit_curve()
srp_public() = key_integer()
Where is A
or B
from SRP design
srp_private() = key_integer()
Where is a
or b
from SRP design
srp_gen_params() =
{user, srp_user_gen_params()} | {host, srp_host_gen_params()}
srp_comp_params() =
{user, srp_user_comp_params()} |
{host, srp_host_comp_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'
Public Key Ciphers
pk_encrypt_decrypt_algs() = rsa
Algorithms for public key encrypt/decrypt. Only RSA is supported.
pk_encrypt_decrypt_opts() = [rsa_opt()] | rsa_compat_opts()
rsa_opt() =
{rsa_padding, rsa_padding()} |
{signature_md, atom()} |
{rsa_mgf1_md, sha} |
{rsa_oaep_label, binary()} |
{rsa_oaep_md, sha}
rsa_padding() =
rsa_pkcs1_padding | rsa_pkcs1_oaep_padding |
rsa_sslv23_padding | rsa_x931_padding | rsa_no_padding
Options for public key encrypt/decrypt. Only RSA is supported.
The RSA options are experimental.
The exact set of options and there syntax may be changed without prior notice.
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.
Public Key Sign and Verify
pk_sign_verify_algs() = rsa | dss | ecdsa | eddsa
Algorithms for sign and verify.
pk_sign_verify_opts() = [rsa_sign_verify_opt()]
rsa_sign_verify_opt() =
{rsa_padding, rsa_sign_verify_padding()} |
{rsa_pss_saltlen, integer()} |
{rsa_mgf1_md, sha2()}
rsa_sign_verify_padding() =
rsa_pkcs1_padding | rsa_pkcs1_pss_padding | rsa_x931_padding |
rsa_no_padding
Options for sign and verify.
The RSA options are experimental.
The exact set of options and there syntax may be changed without prior notice.
Diffie-Hellman Keys and parameters
dh_params() = [key_integer()]
dh_params() = [P, G] | [P, G, PrivateKeyBitLength]
ecdh_public() = key_integer()
ecdh_private() = key_integer()
ecdh_params() =
ec_named_curve() | edwards_curve_dh() | ec_explicit_curve()
Types for Engines
engine_key_ref() =
#{engine := engine_ref(),
key_id := key_id(),
password => password(),
term() => term()}
engine_ref() = term()
The result of a call to engine_load/3
.
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.
password() = string() | binary()
The password of the key stored in an engine.
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
engine_cmnd() = {unicode:chardata(), unicode:chardata()}
Pre and Post commands for engine_load/3 and /4
.
Internal data types
crypto_state()
hash_state()
hmac_state()
mac_state()
stream_state()
Contexts with an internal state that should not be manipulated but passed between function calls.
Error types
run_time_error() = any()
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/0
.
descriptive_error() = any()
This is a more developed variant of the older run_time_error()
.
The exception is:
{Tag, {C_FileName,LineNumber}, Description} Tag = badarg | notsup | error C_FileName = string() LineNumber = integer() Description = string()
It is like the older type an exception of the error
class. In addition they contain a descriptive text in English. That text is targeted to a developer. Examples are "Bad key size" or "Cipher id is not an atom".
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.
To catch the exception, use for example:
try crypto:crypto_init(Ciph, Key, IV, true) catch error:{Tag, {C_FileName,LineNumber}, Description} -> do_something(......) ..... end
New API
Exports
crypto_init(Cipher, Key, FlagOrOptions) -> State | descriptive_error() | OTP 22.0 |
Types
Part of the new API
.
Equivalent to the call crypto_init(Cipher, Key, <<>>, FlagOrOptions)
. It is intended for ciphers without an IV (nounce).
crypto_init(Cipher, Key, IV, FlagOrOptions) -> State | descriptive_error() | OTP 22.0 |
Types
Part of the new API
. Initializes a series of encryptions or decryptions and creates an internal state with a reference that is returned.
If IV = <<>>
, no IV is used. This is intended for ciphers without an IV (nounce). See crypto_init/3
.
If IV = undefined
, the IV must be added by calls to crypto_dyn_iv_update/3
. This is intended for cases where the IV (nounce) need to be changed for each encryption and decryption. See crypto_dyn_iv_init/3
.
The actual encryption or decryption is done by crypto_update/2
(or crypto_dyn_iv_update/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 specifed 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
.
See examples in the User's Guide.
crypto_update(State, Data) -> Result | descriptive_error() | OTP 22.0 |
Types
Part of the new API
. It does an actual crypto operation on a part of the full text. 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
.
See examples in the User's Guide.
crypto_dyn_iv_init(Cipher, Key, FlagOrOptions) -> State | descriptive_error() | OTP 22.0 |
Types
Part of the new API
.
Initializes a series of encryptions or decryptions where the IV is provided later. The actual encryption or decryption is done by crypto_dyn_iv_update/3
.
The function is equivalent to crypto_init(Cipher, Key, undefined, FlagOrOptions)
.
crypto_final(State) -> FinalResult | descriptive_error() |
Types
Part of the new API
.
Finalizes a series of encryptions or decryptions 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,4
or crypto_dyn_iv_init/3
.
crypto_get_data(State) -> Result |
Types
Part of the new API
.
Returns information about the State in the argument. The information is the form of 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 ot
crypto_init/3,4
. encrypt
- Is
true
if encryption is performed. It isfalse
otherwise.
crypto_dyn_iv_update(State, Data, IV) -> Result | descriptive_error() | OTP 22.0 |
Types
Part of the new API
. Do an actual crypto operation on a part of the full text and the IV is supplied for each part. The State
should be created with crypto_dyn_iv_init/3
.
crypto_one_time(Cipher, Key, Data, FlagOrOptions) -> Result | descriptive_error() | OTP 22.0 |
Types
As crypto_one_time/5
but for ciphers without IVs.
crypto_one_time(Cipher, Key, IV, Data, FlagOrOptions) -> Result | descriptive_error() | OTP 22.0 |
Types
Part of the new API
. Do a complete encrypt or decrypt of the full text in the argument Data
.
For encryption, set the FlagOrOptions
to true
. For decryption, set it to false
. For setting other options, see crypto_init/4
.
See examples in the User's Guide.
OTP 22.0 |
crypto_one_time_aead(Cipher, Key, IV, InText, AAD, TagOrTagLength, EncFlag) -> Result | descriptive_error() | OTP 22.0 |
Types
Part of the new API
. 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_aead/6
form may be used.
For decryption, set the EncryptFlag
to false
and put the tag to be checked in the argument TagOrTagLength
.
See examples in the User's Guide.
supports(Type) -> Support | OTP 22.0 |
Types
Can be used to determine 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.
mac(Type :: poly1305, Key, Data) -> Mac | descriptive_error() | OTP 22.1 |
Types
Short for mac(Type, undefined, Key, Data)
.
mac(Type, SubType, Key, Data) -> Mac | descriptive_error() | OTP 22.1 |
Types
Computes a MAC (Message Authentication Code) of type Type
from Data
.
SubType
depends on the MAC Type
:
- For
hmac
it is a hash algorithm, seeAlgorithm Details
in the User's Guide. - For
cmac
it is a cipher suitable for cmac, seeAlgorithm Details
in the User's Guide. - For
poly1305
it should be set toundefined
or themac/2
function could be used instead, seeAlgorithm 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.
macN(Type :: poly1305, Key, Data, MacLength) -> Mac | descriptive_error() | OTP 22.1 |
Types
Short for macN(Type, undefined, Key, Data, MacLength)
.
macN(Type, SubType, Key, Data, MacLength) -> Mac | descriptive_error() | OTP 22.1 |
Types
Computes a MAC (Message Authentication Code) as 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.
mac_init(Type :: poly1305, Key) -> State | descriptive_error() | OTP 22.1 |
Types
Short for mac_init(Type, undefined, Key)
.
mac_init(Type, SubType, Key) -> State | descriptive_error() | OTP 22.1 |
Types
Initializes the context for streaming MAC operations.
Type
determines which mac algorithm to use in the MAC operation.
SubType
depends on the MAC Type
:
- For
hmac
it is a hash algorithm, seeAlgorithm Details
in the User's Guide. - For
cmac
it is a cipher suitable for cmac, seeAlgorithm Details
in the User's Guide. - For
poly1305
it should be set toundefined
or themac/2
function could be used instead, seeAlgorithm 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
.
See examples in the User's Guide.
mac_update(State0, Data) -> State | descriptive_error() | OTP 22.1 |
Types
Updates 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 a previous call of mac_update/2
. The value State0
is returned unchanged by the function as State
.
mac_final(State) -> Mac | descriptive_error() | OTP 22.1 |
Types
Finalizes the MAC operation referenced by State
. 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.
mac_finalN(State, MacLength) -> Mac | descriptive_error() | OTP 22.1 |
Types
Finalizes the MAC operation referenced by State
.
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.
API kept from previous versions
Exports
bytes_to_integer(Bin :: binary()) -> integer() | OTP R16B01 |
Convert binary representation, of an integer, to an Erlang integer.
compute_key(Type, OthersPublicKey, MyPrivateKey, Params) -> SharedSecret | OTP R16B01 |
Types
Computes the shared secret from the private key and the other party's public key. See also public_key:compute_key/2
exor(Bin1 :: iodata(), Bin2 :: iodata()) -> binary() |
Performs bit-wise XOR (exclusive or) on the data supplied.
generate_key(Type, Params) -> {PublicKey, PrivKeyOut} | OTP R16B01 |
generate_key(Type, Params, PrivKeyIn) -> {PublicKey, PrivKeyOut} | OTP R16B01 |
Types
Generates a public key of type Type
. See also public_key:generate_key/1
. May raise exception:
-
error:badarg
: an argument is of wrong type or has an illegal value, -
error:low_entropy
: the random generator failed due to lack of secure "randomness", -
error:computation_failed
: the computation fails of another reason thanlow_entropy
.
RSA key generation is only available if the runtime was built with dirty scheduler support. Otherwise, attempting to generate an RSA key will raise exception error:notsup
.
hash(Type, Data) -> Digest | OTP R15B02 |
Types
Computes a message digest of type Type
from Data
.
May raise exception error:notsup
in case the chosen Type
is not supported by the underlying libcrypto implementation.
hash_init(Type) -> State | OTP R15B02 |
Types
Initializes the context for streaming hash operations. Type
determines which digest to use. The returned context should be used as argument to hash_update
.
May raise exception error:notsup
in case the chosen Type
is not supported by the underlying libcrypto implementation.
hash_update(State, Data) -> NewState | OTP R15B02 |
Types
Updates the digest represented by Context
using the given Data
. Context
must have been generated using hash_init
or a previous call to this function. Data
can be any length. NewContext
must be passed into the next call to hash_update
or hash_final
.
hash_final(State) -> Digest | OTP R15B02 |
Types
Finalizes the hash operation referenced by Context
returned from a previous call to hash_update
. The size of Digest
is determined by the type of hash function used to generate it.
info_fips() -> not_supported | not_enabled | enabled | OTP 20.0 |
Provides information about 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.
In FIPS mode all non-FIPS compliant algorithms are disabled and raise exception error:notsup
. Check supports
that in FIPS mode returns the restricted list of available algorithms.
enable_fips_mode(Enable) -> Result | OTP 21.1 |
Types
Enables (Enable = true
) or disables (Enable = false
) FIPS mode. Returns true
if the operation was successful or false
otherwise.
Note that to enable FIPS mode succesfully, OTP must be built with the configure option --enable-fips
, and the underlying libcrypto must also support FIPS.
See also info_fips/0
.
info_lib() -> [{Name, VerNum, VerStr}] |
Types
Provides 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"">>}]
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.
hash_info(Type) -> Result | run_time_error() | OTP 22.0 |
Types
Provides 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/0
.
cipher_info(Type) -> Result | run_time_error() | OTP 22.0 |
Types
Provides a map with information about block_size, key_length, iv_length and possibly other properties of the cipher algorithm in question.
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. Therefor 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/0
.
mod_pow(N, P, M) -> Result | OTP R16B01 |
Types
Computes the function N^P mod M
.
next_iv(Type :: cbc_cipher() , Data) -> NextIVec | OTP R16B01 |
next_iv(Type :: des_cfb, Data, IVec) -> NextIVec | OTP R16B01 |
Types
Returns the initialization vector to be used in the next iteration of encrypt/decrypt of type Type
. Data
is the encrypted data from the previous iteration step. The IVec
argument is only needed for des_cfb
as the vector used in the previous iteration step.
private_decrypt(Algorithm, CipherText, PrivateKey, Options) -> PlainText | OTP R16B01 |
Types
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]
private_encrypt(Algorithm, PlainText, PrivateKey, Options) -> CipherText | OTP R16B01 |
Types
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]
public_decrypt(Algorithm, CipherText, PublicKey, Options) -> PlainText | OTP R16B01 |
Types
Decrypts the CipherText
, encrypted with private_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_public/[2,3]
public_encrypt(Algorithm, PlainText, PublicKey, Options) -> CipherText | OTP R16B01 |
Types
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]
rand_seed(Seed :: binary()) -> ok | OTP 17.0 |
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
rand_uniform(Lo, Hi) -> N |
Types
Generate a random number N, Lo =< N < Hi.
Uses the crypto
library pseudo-random number generator. Hi
must be larger than Lo
.
start() -> ok | {error, Reason :: term()} |
Equivalent to application:start(crypto).
stop() -> ok | {error, Reason :: term()} |
Equivalent to application:stop(crypto).
strong_rand_bytes(N :: integer() >= 0) -> binary() | OTP R14B03 |
Generates N bytes randomly uniform 0..255, and returns the result in a binary. 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".
rand_seed() -> rand:state() | OTP 20.0 |
Creates state object for random number generation
, in order to generate cryptographically strong random numbers (based on OpenSSL's BN_rand_range
), and saves it 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[
rand_seed_s() -> rand:state() | OTP 20.0 |
Creates 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".
The state returned from this function cannot be used to get a reproducable random sequence as from the other rand
functions, since reproducability does not match cryptographically safe.
The only supported usage is to generate one distinct random sequence from this start state.
rand_seed_alg(Alg) -> rand:state() | OTP 21.0 |
Types
Creates state object for random number generation
, in order to generate cryptographically strong random numbers, and saves it 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[
rand_seed_alg(Alg, Seed) -> rand:state() | OTP-22.0 |
Types
Creates a state object for random number generation
, in order to generate cryptographically unpredictable random numbers, and saves it 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
rand_seed_alg_s(Alg) -> rand:state() | OTP 21.0 |
Types
Creates 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
.
When using the state object from this function the rand
functions using it may throw exception low_entropy
in case the random generator failed due to lack of secure "randomness".
The state returned from this function cannot be used to get a reproducable random sequence as from the other rand
functions, since reproducability 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.
rand_seed_alg_s(Alg, Seed) -> rand:state() | OTP 22.0 |
Types
Creates 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
withAlg =:= crypto
orAlg =:= 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
.
ec_curves() -> [EllipticCurve] | OTP 17.0 |
Types
Can be used to determine which named elliptic curves are supported.
ec_curve(CurveName) -> ExplicitCurve | OTP 17.0 |
Types
Return the defining parameters of a elliptic curve.
sign(Algorithm, DigestType, Msg, Key) -> Signature | OTP R16B01 |
sign(Algorithm, DigestType, Msg, Key, Options) -> Signature | OTP 20.1 |
Types
Creates 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
.
See also public_key:sign/3
.
verify(Algorithm, DigestType, Msg, Signature, Key) -> Result | OTP R16B01 |
verify(Algorithm, DigestType, Msg, Signature, Key, Options) -> Result | OTP 20.1 |
Types
Verifies 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
.
See also public_key:verify/4
.
Engine API
Exports
privkey_to_pubkey(Type, EnginePrivateKeyRef) -> PublicKey | OTP 20.2 |
Types
Fetches the corresponding public key from a private key stored in an Engine. The key must be of the type indicated by the Type parameter.
engine_get_all_methods() -> Result | OTP 20.2 |
Types
Returns 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.
engine_load(EngineId, PreCmds, PostCmds) -> Result | OTP 20.2 |
Types
Loads the OpenSSL engine given by EngineId
if it is available and then returns ok and an engine handle. This function is the same as calling engine_load/4
with EngineMethods
set to a list of all the possible methods. An error tuple is returned if the engine can't be loaded.
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.
engine_load(EngineId, PreCmds, PostCmds, EngineMethods) -> Result | OTP 20.2 |
Types
Loads the OpenSSL engine given by EngineId
if it is available and then returns ok and an engine handle. An error tuple is returned if the engine can't be loaded.
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.
engine_unload(Engine) -> Result | OTP 20.2 |
Types
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.
engine_by_id(EngineId) -> Result | OTP 21.0.6 |
Types
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.
engine_ctrl_cmd_string(Engine, CmdName, CmdArg) -> Result | OTP 20.2 |
Types
Sends ctrl commands to the OpenSSL engine given by 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.
engine_ctrl_cmd_string(Engine, CmdName, CmdArg, Optional) -> Result | OTP 20.2 |
Types
Sends ctrl commands to the OpenSSL engine given by 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.
engine_add(Engine) -> Result | OTP 21.0.6 |
Types
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.
engine_remove(Engine) -> Result | OTP 21.0.6 |
Types
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.
engine_get_id(Engine) -> EngineId | OTP 21.0.6 |
Types
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.
engine_get_name(Engine) -> EngineName | OTP 21.0.6 |
Types
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.
engine_list() -> Result | OTP 20.2 |
Types
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.
ensure_engine_loaded(EngineId, LibPath) -> Result | OTP 21.0.6 |
Types
Loads the OpenSSL engine given by EngineId
and the path to the dynamic library implementing the engine. This function is the same as calling ensure_engine_loaded/3
with EngineMethods
set to a list of all the possible methods. An error tuple is returned if the engine can't be loaded.
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.
ensure_engine_loaded(EngineId, LibPath, EngineMethods) -> Result | OTP 21.0.6 |
Types
Loads the OpenSSL engine given by EngineId
and the path to the dynamic library implementing the engine. This function differs from the normal engine_load in that sense it also add the engine id to the internal list in OpenSSL. Then in the following calls to the function it just fetch the reference to the engine instead of loading it again. An error tuple is returned if the engine can't be loaded.
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.
ensure_engine_unloaded(Engine) -> Result | OTP 21.0.6 |
Types
Unloads an engine loaded with the ensure_engine_loaded
function. It both removes the label from the OpenSSL internal engine list and unloads the engine. This function is the same as calling ensure_engine_unloaded/2
with EngineMethods
set to a list of all the possible methods. An error tuple is returned if the engine can't be unloaded.
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.
ensure_engine_unloaded(Engine, EngineMethods) -> Result | OTP 21.0.6 |
Types
Unloads an engine loaded with the ensure_engine_loaded
function. It both removes the label from the OpenSSL internal engine list and unloads the engine. An error tuple is returned if the engine can't be unloaded.
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.
Old API
Exports
block_encrypt(Type :: block_cipher_without_iv() ,Key :: key() ,PlainText :: iodata()) -> binary() | run_time_error() | OTP 18.0 |
Don't use this function for new programs! Use the-new-api
.
Encrypt PlainText
according to Type
block cipher.
May raise exception error:notsup
in case the chosen Type
is not supported by the underlying libcrypto implementation.
For keylengths and blocksizes see the User's Guide
.
block_decrypt(Type :: block_cipher_without_iv() ,Key :: key() ,Data :: iodata()) -> binary() | run_time_error() | OTP 18.0 |
Don't use this function for new programs! Use the new api
.
Decrypt CipherText
according to Type
block cipher.
May raise exception error:notsup
in case the chosen Type
is not supported by the underlying libcrypto implementation.
For keylengths and blocksizes see the User's Guide
.
block_encrypt(Type, Key, Ivec, PlainText) -> CipherText | Error | OTP R16B01 |
block_encrypt(AeadType, Key, Ivec, {AAD, PlainText}) -> {CipherText, CipherTag} | Error | OTP R16B01 |
block_encrypt(aes_gcm | aes_ccm, Key, Ivec, {AAD, PlainText, TagLength}) -> {CipherText, CipherTag} | Error | OTP R16B01 |
Types
Don't use this function for new programs! Use the new api
.
Encrypt PlainText
according to Type
block cipher. IVec
is an arbitrary initializing vector.
In AEAD (Authenticated Encryption with Associated Data) mode, encrypt PlainText
according to Type
block cipher and calculate CipherTag
that also authenticates the AAD
(Associated Authenticated Data).
May raise exception error:notsup
in case the chosen Type
is not supported by the underlying libcrypto implementation.
For keylengths, iv-sizes and blocksizes see the User's Guide
.
block_decrypt(Type, Key, Ivec, CipherText) -> PlainText | Error | OTP R16B01 |
block_decrypt(AeadType, Key, Ivec, {AAD, CipherText, CipherTag}) -> PlainText | Error | OTP R16B01 |
Types
Don't use this function for new programs! Use the new api
.
Decrypt CipherText
according to Type
block cipher. IVec
is an arbitrary initializing vector.
In AEAD (Authenticated Encryption with Associated Data) mode, decrypt CipherText
according to Type
block cipher and check the authenticity the PlainText
and AAD
(Associated Authenticated Data) using the CipherTag
. May return error
if the decryption or validation fail's
May raise exception error:notsup
in case the chosen Type
is not supported by the underlying libcrypto implementation.
For keylengths, iv-sizes and blocksizes see the User's Guide
.
stream_init(Type, Key) -> State | run_time_error() | OTP R16B01 |
Types
Don't use this function for new programs! Use the new api
.
Initializes the state for use in RC4 stream encryption stream_encrypt
and stream_decrypt
For keylengths see the User's Guide
.
stream_init(Type, Key, IVec) -> State | run_time_error() | OTP R16B01 |
Types
Don't use this function for new programs! Use the new api
.
Initializes the state for use in streaming AES encryption using Counter mode (CTR). Key
is the AES key and must be either 128, 192, or 256 bits long. IVec
is an arbitrary initializing vector of 128 bits (16 bytes). This state is for use with stream_encrypt
and stream_decrypt
.
For keylengths and iv-sizes see the User's Guide
.
stream_encrypt(State, PlainText) -> {NewState, CipherText} | run_time_error() | OTP R16B01 |
Types
Don't use this function for new programs! Use the new api
.
Encrypts PlainText
according to the stream cipher Type
specified in stream_init/3. Text
can be any number of bytes. The initial State
is created using stream_init
. NewState
must be passed into the next call to stream_encrypt
.
stream_decrypt(State, CipherText) -> {NewState, PlainText} | run_time_error() | OTP R16B01 |
Types
Don't use this function for new programs! Use the new api
.
Decrypts CipherText
according to the stream cipher Type
specified in stream_init/3. PlainText
can be any number of bytes. The initial State
is created using stream_init
. NewState
must be passed into the next call to stream_decrypt
.
supports() -> [Support] | OTP R16B01 |
Types
Don't use this function for new programs! Use supports/1
in the new api
.
Can be used to determine 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.
hmac(Type, Key, Data) -> Mac | OTP R16B |
hmac(Type, Key, Data, MacLength) -> Mac | OTP R16B |
Types
Computes a HMAC of type Type
from Data
using Key
as the authentication key.
MacLength
will limit the size of the resultant Mac
.
hmac_init(Type, Key) -> State | OTP R14B03 |
Types
Don't use this function for new programs! Use mac_init/3
in the new api
.
Initializes the context for streaming HMAC operations. Type
determines which hash function to use in the HMAC operation. Key
is the authentication key. The key can be any length.
hmac_update(State, Data) -> NewState | OTP R14B03 |
Types
Don't use this function for new programs! Use mac_update/2
in the new api
.
Updates the HMAC represented by Context
using the given Data
. Context
must have been generated using an HMAC init function (such as hmac_init
). Data
can be any length. NewContext
must be passed into the next call to hmac_update
or to one of the functions hmac_final
and hmac_final_n
Do not use a Context
as argument in more than one call to hmac_update or hmac_final. The semantics of reusing old contexts in any way is undefined and could even crash the VM in earlier releases. The reason for this limitation is a lack of support in the underlying libcrypto API.
hmac_final(State) -> Mac | OTP R14B03 |
Types
Don't use this function for new programs! Use mac_final/1
in the new api
.
Finalizes the HMAC operation referenced by Context
. The size of the resultant MAC is determined by the type of hash function used to generate it.
hmac_final_n(State, HashLen) -> Mac | OTP R14B03 |
Types
Don't use this function for new programs! Use mac_finalN/2
in the new api
.
Finalizes the HMAC operation referenced by Context
. HashLen
must be greater than zero. Mac
will be a binary with at most HashLen
bytes. Note that if HashLen is greater than the actual number of bytes returned from the underlying hash, the returned hash will have fewer than HashLen
bytes.
cmac(Type, Key, Data) -> Mac | OTP 20.0 |
cmac(Type, Key, Data, MacLength) -> Mac | OTP 20.0 |
Types
Computes a CMAC of type Type
from Data
using Key
as the authentication key.
MacLength
will limit the size of the resultant Mac
.
poly1305(Key :: iodata(), Data :: iodata()) -> Mac | OTP 21.1 |
Types
© 2010–2020 Ericsson AB
Licensed under the Apache License, Version 2.0.