crypto(3erl)

๐Ÿ“ฆ
version 25.3.2.8 ยท 5 versions
, in ubuntu noble

๐Ÿ’– crypto(3erl) ๐Ÿ’–

okay bestie, this is the crypto(3erl) page โ€” an Erlang Module Definition for crypto, and it is literally the module that hands you a whole set of cryptographic functions. main character energy fr fr ๐Ÿ”ฅ

๐ŸŒธ NAME ๐ŸŒธ

crypto โ€” Crypto Functions ๐Ÿ‘‘

โœจ DESCRIPTION โœจ

This module provides a set of cryptographic functions. That's the whole vibe, and it's giving extremely useful ๐Ÿซถ

๐Ÿ” Hash functions ๐Ÿ”

  • SHA1, SHA2: Secure Hash Standard [FIPS PUB 180-4]
  • SHA3: SHA-3 Standard: Permutation-Based Hash and Extendable-Output Functions [FIPS PUB 202]
  • BLAKE2: BLAKE2 โ€” fast secure hashing
  • MD5: The MD5 Message Digest Algorithm [RFC 1321]
  • MD4: The MD4 Message Digest Algorithm [RFC 1320]

๐ŸŽ€ 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]

๐Ÿ‘‘ Asymmetric Ciphers - Public Key Techniques ๐Ÿ‘‘

  • RSA: PKCS #1: RSA Cryptography Specifications [RFC 3447]
  • DSS: Digital Signature Standard (DSS) [FIPS 186-4]
  • ECDSA: Elliptic Curve Digital Signature Algorithm [ECDSA]
  • SRP: The SRP Authentication and Key Exchange System [RFC 2945]

๐Ÿ“ Note ๐Ÿ“

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

โš ๏ธ Heads up, bestie: Enabling FIPS mode will also disable algorithms and features. No cap.

The CRYPTO User's Guide has more information on FIPS, Engines and Algorithm Details like key lengths. ๐Ÿ’…โœจ

๐Ÿ’– DATA TYPES ๐Ÿ’–

okay bestie, this is the type dictionary part of the page โ€” the whole cast of characters the CRYPTO app works with. no cap, every type matters here, so let's get into it. โœจ

๐Ÿงš Ciphers ๐Ÿงš

       cipher() = cipher_no_iv() | cipher_iv() | cipher_aead()

       cipher_no_iv() =
           aes_128_ecb | aes_192_ecb | aes_256_ecb | aes_ecb |
           blowfish_ecb | des_ecb | rc4

       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 | 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_ccm |
           aes_128_gcm | aes_192_gcm | aes_256_gcm | aes_gcm |
           chacha20_poly1305

These are the ciphers known by the CRYPTO application. Note that this list might be reduced if the underlying libcrypto does not support all of them. sad but true ๐Ÿ˜ญ

       crypto_opts() = boolean() | [crypto_opt()]

       crypto_opt() = {encrypt, boolean()} | {padding, padding()}

This is your little options menu: it selects encryption with {encrypt,true} or decryption with {encrypt,false}. slay.

       padding() = cryptolib_padding() | otp_padding()

This option handles padding in the last block. If it's not set, no padding is done and any bytes in the last unfilled block is silently discarded. gone, reduced to atoms. ๐Ÿ’€

       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. iykyk ๐Ÿงš

       otp_padding() = zero | random

Erlang/OTP adds either padding of zeroes or padding with random bytes. ๐Ÿ’…

๐ŸŒธ 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 | aes_cbc |
           aes_128_cfb128 | aes_192_cfb128 | aes_256_cfb128 |
           aes_cfb128 | aes_128_cfb8 | aes_192_cfb8 | aes_256_cfb8 |
           aes_cfb8 | blowfish_cbc | des_cbc | des_ede3_cbc | rc2_cbc

       rsa_digest_type() = sha1() | sha2() | md5 | ripemd160

       dss_digest_type() = sha1() | sha2()

       ecdsa_digest_type() = sha1() | sha2()

       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. so like, don't make them your main character for new stuff, mkay? ๐Ÿ™ˆ

๐Ÿฆ‹ 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. just a little vibe check for your deployment. ๐Ÿ‘‘

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

That's the parametric curve definition, bestie. ๐ŸŽ€

       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, served fresh. ๐Ÿ“

๐Ÿ’œ Keys ๐Ÿ’œ

       key_integer() = integer() | binary()

Always binary() when used as return value. no cap.

๐Ÿซถ Public/Private Keys ๐Ÿซถ

       rsa_public() = [key_integer()]

       rsa_private() = [key_integer()]

       rsa_params() =
           {ModulusSizeInBits :: integer(),
            PublicExponent :: key_integer()}

okay so rsa_public() = [E, N] and 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() = [key_integer()]

       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. ๐Ÿ’…

       ecdsa_public() = key_integer()

       ecdsa_private() = key_integer()

       ecdsa_params() = ec_named_curve() | ec_explicit_curve()

ECDSA keys are just key_integer()s, and the params are either a named curve or an explicit curve. iconic.

       eddsa_public() = key_integer()

       eddsa_private() = key_integer()

       eddsa_params() = edwards_curve_ed()

EdDSA same energy: public and private are key_integer(), params are edwards_curve_ed(). โœจ

       srp_public() = key_integer()

       srp_private() = key_integer()

srp_public() = key_integer() โ€” where it's A or B from SRP design.

srp_private() = key_integer() โ€” where it's 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()}

       srp_user_gen_params() = [DerivedKey::binary(), Prime::binary(), Generator::binary(), Version::atom()]

       srp_host_gen_params() = [Verifier::binary(), Prime::binary(), Version::atom() ]

       srp_user_comp_params() = [DerivedKey::binary(), Prime::binary(), Generator::binary(), Version::atom() | ScramblerArg::list()]

       srp_host_comp_params() = [Verifier::binary(), Prime::binary(), Version::atom() | ScramblerArg::list()]

Where Verifier is v, Generator is g and Prime is N, DerivedKey is X, and Scrambler is u (optional, will be generated if not provided) from SRP design.

Version = '3' | '6' | '6a' โ€” periodt. ๐Ÿ’–

๐Ÿ”ฅ Public Key Ciphers ๐Ÿ”ฅ

       pk_encrypt_decrypt_algs() = rsa

Algorithms for public key encrypt/decrypt. Only RSA is supported. that's the whole list, bestie.

       pk_encrypt_decrypt_opts() = [rsa_opt()] | rsa_compat_opts()

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

       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
โš ๏ธ Warning: The RSA options are experimental. The exact set of options and their 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. don't do it, bestie. ๐Ÿ’€

โญ Public Key Sign and Verify โญ

       pk_sign_verify_algs() = rsa | dss | ecdsa | eddsa

Algorithms for sign and verify. the lineup.

       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.

โš ๏ธ Warning: The RSA options are experimental. The exact set of options and their syntax may be changed without prior notice. ๐Ÿ™ˆ

๐ŸŒˆ Diffie-Hellman Keys and parameters ๐ŸŒˆ

       dh_public() = key_integer()

       dh_private() = key_integer()

       dh_params() = [key_integer()]

dh_params() = [P, G] | [P, G, PrivateKeyBitLength] โ€” slay.

       ecdh_public() = key_integer()

       ecdh_private() = key_integer()

       ecdh_params() =
           ec_named_curve() | edwards_curve_dh() | ec_explicit_curve()

ECDH params can be a named curve, an Edwards curve for DH, or an explicit curve. ๐Ÿ’œ

๐ŸŽ€ Types for Engines ๐ŸŽ€

       engine_key_ref() =
           #{engine := engine_ref(),
             key_id := key_id(),
             password => password(),
             term() => term()}

       engine_ref() = term()

engine_ref() is 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. iykyk.

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

       mac_state()

Contexts with an internal state that should not be manipulated but passed between function calls. don't touch the internals, bestie โ€” just pass them along. ๐Ÿ’…

๐Ÿ’… EXCEPTIONS ๐Ÿ’…

okay so bestie, before we get into the actual functions, we gotta talk about how this module tells you something went wrong ๐Ÿ˜ญ there's literally two whole styles and you need to know both, no cap.

โœจ Atoms โ€” the older style โœจ

So back in the day, errors were just plain atoms. Vintage. Iconic in a "we don't do that anymore" kinda way ๐ŸŽ€

  • The exception error:badarg signifies that one or more arguments are of wrong data type, or are otherwise badly formed. iykyk, you passed something cursed ๐Ÿ’€
  • 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 ๐Ÿฆ‹

Okay so this is the glow-up. Now the exception looks like this:

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

And the tags themselves, because you will meet them:

  • badarg โ€” signifies that one or more arguments are of wrong data type or are otherwise badly formed. same energy as before, just wrapped in a lil tuple now ๐Ÿซถ
  • 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. like literally, you're gonna be grepping C files at 2am ๐Ÿ˜ญ

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

see, told you it slays ๐Ÿ’…


๐Ÿ”ฅ EXPORTS ๐Ÿ”ฅ

okay this is the main character section, buckle up ๐ŸŽ€ everything below uses the shiny 3-tuple style for error handling, bestie. periodt.

๐ŸŒธ crypto_init(Cipher, Key, FlagOrOptions) -> State

Types:

Cipher = cipher_no_iv()
Key = iodata()
FlagOrOptions = crypto_opts() | boolean()
State = crypto_state()

Uses the 3-tuple style for error handling.

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

๐Ÿฆ‹ crypto_init(Cipher, Key, IV, FlagOrOptions) -> State

Types:

Cipher = cipher_iv()
Key = IV = iodata()
FlagOrOptions = crypto_opts()
State = crypto_state()

Uses the 3-tuple style for error handling.

Initializes a series of encryptions or decryptions and creates an internal state with a reference that is returned. that reference is your lil handle for everything that follows, guard it with your life ๐Ÿ’–

  • 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. like, you're on your own for that one ๐Ÿ™ˆ

โš ๏ธ bestie listen: 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. silently!! the audacity ๐Ÿ’€

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

Types:

State = crypto_state()
Data = iodata()
Result = binary()

Uses the 3-tuple style for error handling.

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. it's literally hoarding your leftover bytes for next time, generous queen ๐Ÿ’…

See examples in the User's Guide.

๐Ÿงš crypto_dyn_iv_init(Cipher, Key, FlagOrOptions) -> State

Types:

Cipher = cipher_iv()
Key = iodata()
FlagOrOptions = crypto_opts() | boolean()
State = crypto_state()

Uses the 3-tuple style for error handling.

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). the undefined is doing all the work here, lowkey iconic ๐Ÿฆ‹

โญ crypto_final(State) -> FinalResult

Types:

State = crypto_state()
FinalResult = binary()

Uses the 3-tuple style for error handling.

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. empty is fine, don't panic ๐Ÿซถ

๐Ÿ’œ crypto_get_data(State) -> Result

Types:

State = crypto_state()
Result = map()

Uses the 3-tuple style for error handling.

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 to crypto_init/3,4.
  • encrypt โ€” is true if encryption is performed. It is false otherwise.

a whole map of gossip about your state, we love a receipts moment ๐Ÿ”ฅ

๐ŸŒˆ crypto_dyn_iv_update(State, Data, IV) -> Result

Types:

State = crypto_state()
Data = IV = iodata()
Result = binary()

Uses the 3-tuple style for error handling.

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. fresh IV every time, main character energy โœจ

๐Ÿ“ crypto_one_time(Cipher, Key, Data, FlagOrOptions) -> Result

Types:

Cipher = cipher_no_iv()
Key = Data = iodata()
FlagOrOptions = crypto_opts() | boolean()
Result = binary()

Uses the 3-tuple style for error handling.

As crypto_one_time/5 but for ciphers without IVs. the no-IV remix ๐Ÿ’…

๐Ÿ‘‘ crypto_one_time(Cipher, Key, IV, Data, FlagOrOptions) -> Result

Types:

Cipher = cipher_iv()
Key = IV = Data = iodata()
FlagOrOptions = crypto_opts() | boolean()
Result = binary()

Uses the 3-tuple style for error handling.

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. ๐ŸŽ€

๐Ÿฆ‹ crypto_one_time_aead(Cipher, Key, IV, InText, AAD, EncFlag :: true) -> Result

๐Ÿฆ‹ crypto_one_time_aead(Cipher, Key, IV, InText, AAD, TagOrTagLength, EncFlag) -> Result

Types:

Cipher = cipher_aead()
Key = IV = InText = AAD = iodata()
TagOrTagLength = EncryptTagLength | DecryptTag
EncryptTagLength = integer() >= 0
DecryptTag = iodata()
EncFlag = boolean()
Result = EncryptResult | DecryptResult
EncryptResult = {OutCryptoText, OutTag}
DecryptResult = OutPlainText | error
OutCryptoText = OutTag = OutPlainText = binary()

Uses the 3-tuple style for error handling.

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

Types:

Type = hashs | ciphers | public_keys | macs | curves | rsa_opts
Support = Hashs | Ciphers | PKs | Macs | Curves | RSAopts
Hashs = [sha1() | sha2() | sha3() | 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()]

Can be used to determine which crypto algorithms that are supported by the underlying libcrypto library. vibe check on your libcrypto, basically โœจ

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

๐Ÿงš mac(Type :: poly1305, Key, Data) -> Mac

Types:

Key = Data = iodata()
Mac = binary()

Uses the 3-tuple style for error handling.

Short for mac(Type, undefined, Key, Data).

๐ŸŒธ mac(Type, SubType, Key, Data) -> Mac

Types:

Type = hmac | cmac | poly1305
SubType = hmac_hash_algorithm() | cmac_cipher_algorithm() | undefined
Key = Data = iodata()
Mac = binary()

Uses the 3-tuple style for error handling.

Computes a MAC (Message Authentication Code) of type Type from Data.

SubType depends on the MAC Type:

  • For hmac it is a hash algorithm, see Algorithm Details in the User's Guide.
  • cmac ๐Ÿ’… โ€” for cmac it's a cipher that's suitable for cmac, see Algorithm Details in the User's Guide.
  • poly1305 ๐Ÿ“ โ€” for poly1305 it should be set to undefined, orrr you could just use the mac/2 function instead, see Algorithm Details in the User's Guide.

Key is the authentication key, and its length depends on the Type and SubType. Wanna know how long? Peep hash_info/1 (for hmac) and cipher_info/1 (for cmac). For poly1305 the key length is 32 bytes, periodt. Quick heads-up tho: the cryptographic quality of the key is not checked. Like, at all. ๐Ÿ™ˆ

The Mac result will have a default length depending on the Type and SubType. Want it shorter? 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

Types:

Key = Data = iodata()
Mac = binary()
MacLength = integer() >= 1

Uses the 3-tuple style for error handling. ๐Ÿซถ

Short for macN(Type, undefined, Key, Data, MacLength).


๐ŸŽ€ macN(Type, SubType, Key, Data, MacLength) -> Mac

Types:

Type = hmac | cmac | poly1305
SubType =
    hmac_hash_algorithm() | cmac_cipher_algorithm() |
undefined
Key = Data = iodata()
Mac = binary()
MacLength = integer() >= 1

Computes a MAC (Message Authentication Code) just like mac/3 and mac/4, except MacLength caps the size of the resulting Mac at at most MacLength bytes. Lowkey important caveat: if MacLength is greater than the actual number of bytes returned from the underlying hash, the returned hash will just have that shorter length instead. No padding, no drama, it just is what it is. ๐Ÿ’€

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


๐ŸŽ€ mac_init(Type :: poly1305, Key) -> State

Types:

Key = iodata()
State = mac_state()

Uses the 3-tuple style for error handling. ๐Ÿซถ

Short for mac_init(Type, undefined, Key).


๐ŸŽ€ mac_init(Type, SubType, Key) -> State

Types:

Type = hmac | cmac | poly1305
SubType =
    hmac_hash_algorithm() | cmac_cipher_algorithm() |
undefined
Key = iodata()
State = mac_state()

Uses the 3-tuple style for error handling. ๐Ÿซถ

Initializes the context for streaming MAC operations, iykyk. ๐ŸŒŠ

Type decides which mac algorithm gets used in the MAC operation.

SubType depends on the MAC Type:

  • For hmac it's a hash algorithm, see Algorithm Details in the User's Guide. โœจ
  • For cmac it's 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) 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

Types:

Data = iodata()
State0 = State = mac_state()

Uses the 3-tuple style for error handling. ๐Ÿซถ

Updates the MAC represented by State0 using the given Data, which could be of any length. Feed it anything, bestie, it eats. ๐Ÿ”ฅ

State0 is the State value originally from a MAC init function โ€” that's 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. Slay, immutability. ๐Ÿ’œ


๐ŸŽ€ mac_final(State) -> Mac

Types:

State = mac_state()
Mac = binary()

Uses the 3-tuple style for error handling. ๐Ÿซถ

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

Types:

State = mac_state()
MacLength = integer() >= 1
Mac = binary()

Uses the 3-tuple style for error handling. ๐Ÿซถ

Finalizes the MAC operation referenced by State. ๐Ÿ

Mac will be a binary with at most MacLength bytes. And yeah, repeating myself because it matters: 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.


๐ŸŽ€ bytes_to_integer(Bin :: binary()) -> integer()

Converts the binary representation of an integer into an Erlang integer. Clean, simple, iconic. ๐Ÿงฎโœจ


๐ŸŽ€ compute_key(Type, OthersPublicKey, MyPrivateKey, Params) -> SharedSecret

Types:

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

Uses the 3-tuple style for error handling. ๐Ÿซถ

Computes the shared secret from the private key and the other party's public key. It's giving mutual understanding, it's giving agreement. ๐Ÿค See also public_key:compute_key/2.


๐ŸŽ€ exor(Bin1 :: iodata(), Bin2 :: iodata()) -> binary()

Performs bit-wise XOR (exclusive or) on the data supplied. That's it, that's the function. ๐Ÿ’…โšก


๐ŸŽ€ generate_key(Type, Params) -> {PublicKey, PrivKeyOut}

๐ŸŽ€ generate_key(Type, Params, PrivKeyIn) -> {PublicKey, PrivKeyOut}

Types:

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

Uses the 3-tuple style for error handling. ๐Ÿซถ

Generates a public key of type Type. See also public_key:generate_key/1. ๐Ÿ”‘

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()) is one of the MODP groups (see RFC 3526) - and the optional PrivateKeyBitLength parameter (in dh_params()) 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. No cap, those are the numbers. ๐Ÿ“
Note: ๐Ÿšจ RSA key generation is only available if the runtime was built with dirty scheduler support. Otherwise, attempting to generate an RSA key will raise the exception error:notsup. Sad but true. ๐Ÿ˜ญ

๐ŸŽ€ hash(Type, Data) -> Digest

Types:

Type = hash_algorithm()
Data = iodata()
Digest = binary()

Uses the 3-tuple style for error handling. ๐Ÿซถ

Computes a message digest of type Type from Data. One and done, no notes. ๐Ÿงš


๐ŸŽ€ hash_init(Type) -> State

Types:

Type = hash_algorithm()
State = hash_state()

Uses the 3-tuple style for error handling. ๐Ÿซถ

Initializes the context for streaming hash operations. Type determines which digest to use. The returned context should be used as argument to hash_update. ๐ŸŒŠ


๐ŸŽ€ hash_update(State, Data) -> NewState

Types:

State = NewState = hash_state()
Data = iodata()

Uses the 3-tuple style for error handling. ๐Ÿซถ

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. Chain it, bestie. ๐Ÿ”—


๐ŸŽ€ hash_final(State) -> Digest

Types:

State = hash_state()
Digest = binary()

Uses the 3-tuple style for error handling. ๐Ÿซถ

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. It is what it is, and what it is is determined by the algorithm. ๐Ÿ’…


๐ŸŽ€ info_fips() -> not_supported | not_enabled | enabled

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.

Warning: ๐Ÿšจ In FIPS mode all non-FIPS compliant algorithms are disabled and raise exception error:notsup. Check supports(ciphers) โ€” in FIPS mode it returns the restricted list of available algorithms. Don't get caught out, fr fr. ๐Ÿ˜ค

๐ŸŽ€ enable_fips_mode(Enable) -> Result

Types:

Enable = Result = boolean()

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 successfully, OTP must be built with the configure option --enable-fips, and the underlying libcrypto must also support FIPS. Both gotta be in on it. ๐Ÿค

See also info_fips/0.


Provides a map with information about the compilation and linking of crypto. The tea. โ˜•๐Ÿ‘‘

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>

okay so heads up bestie โ€” there might be more association types in that map than the docs even bother to write down, so don't come for me if you spot extras ๐Ÿ‘€โœจ

info_lib() -> [{Name, VerNum, VerStr}]

Types, babes:

Name = binary()
VerNum = integer()
VerStr = binary()

Gives you the name and version of the libraries that crypto is using. ๐ŸŒธ

Name is, like, the name of the library obviously. VerNum is the numeric version following the library's own versioning scheme (their rules, not ours ๐Ÿ’…). And VerStr is the text version of that same version, for the people who prefer words over numbers.

> info_lib().
[{<<"OpenSSL">>,269484095,<<"OpenSSL 1.1.0c  10 Nov 2016"">>}]
Note ๐Ÿ“Œ โ€” From OTP R16 onwards, that numeric version is actually the version of the OpenSSL header files (openssl/opensslv.h) that got used when crypto was compiled. The text variant is the libcrypto library that's used at runtime. In earlier OTP versions, both the numeric and the text came from the library itself. two different things, no cap ๐Ÿซถ

hash_info(Type) -> Result

Types:

Type = hash_algorithm()
Result =
    #{size := integer(),
      block_size := integer(),
      type := integer()}

Hands you a map with the block_size, the size, and possibly other properties of whatever hash algorithm you asked about. little info dump, iconic behaviour ๐ŸŽ€

Wanna know which hash algorithms are even on the menu? go look at supports(hashs).

cipher_info(Type) -> Result

Types:

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

Gives you a map with info about the block_size, the key_length, the iv_length, whether AEAD is supported, and possibly other properties of the cipher algorithm you're asking about ๐Ÿ’–

Note โš ๏ธ โ€” The ciphers aes_cbc, aes_cfb8, aes_cfb128, aes_ctr, aes_ecb, aes_gcm and aes_ccm have no keylength in the Type, unlike for example aes_128_ctr. They just adapt to the length of the key you hand the encrypt and decrypt functions. So yeah โ€” it's literally impossible to return a valid keylength in that map for those. ๐Ÿ˜ญ Always use a Type with an explicit key length. periodt.

Wanna know which cipher algorithms exist? check supports(ciphers).

mod_pow(N, P, M) -> Result

Types:

N = P = M = binary() | integer()
Result = binary() | error

Does the math: computes N^P mod M. big numbers, big brain energy ๐Ÿ”ฅ

private_decrypt(Algorithm, CipherText, PrivateKey, Options) -> PlainText

Types:

Algorithm = pk_encrypt_decrypt_algs()
CipherText = binary()
PrivateKey = rsa_private() | engine_key_ref()
Options = pk_encrypt_decrypt_opts()
PlainText = binary()

Uses the 3-tuple style for error handling.

Decrypts CipherText โ€” which was encrypted with public_encrypt/4 (or some equivalent function) โ€” using the PrivateKey, and hands you back the plaintext (message digest). This one's a low level signature verification operation, the kind older versions of the SSL protocol used. See also public_key:decrypt_private/[2,3] ๐Ÿ’…

private_encrypt(Algorithm, PlainText, PrivateKey, Options) -> CipherText

Types:

Algorithm = pk_encrypt_decrypt_algs()
PlainText = binary()
PrivateKey = rsa_private() | engine_key_ref()
Options = pk_encrypt_decrypt_opts()
CipherText = binary()

Uses the 3-tuple style for error handling.

Encrypts PlainText using the PrivateKey and gives you the ciphertext back. 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

Types:

Algorithm = pk_encrypt_decrypt_algs()
CipherText = binary()
PublicKey = rsa_public() | engine_key_ref()
Options = pk_encrypt_decrypt_opts()
PlainText = binary()

Uses the 3-tuple style for error handling.

Decrypts CipherText โ€” encrypted with private_encrypt/4 (or an equivalent function) using the PrivateKey โ€” and returns the plaintext (message digest). Another low level signature verification operation, the kind older SSL protocol versions leaned on. See also public_key:decrypt_public/[2,3] ๐ŸŒธ

public_encrypt(Algorithm, PlainText, PublicKey, Options) -> CipherText

Types:

Algorithm = pk_encrypt_decrypt_algs()
PlainText = binary()
PublicKey = rsa_public() | engine_key_ref()
Options = pk_encrypt_decrypt_opts()
CipherText = binary()

Uses the 3-tuple style for error handling.

Encrypts PlainText (that's a message digest, bestie) using the PublicKey and returns the CipherText. 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

Sets the seed for the PRNG to whatever binary you pass in. Under the hood this calls the RAND_seed function from openssl. Only use this if the system you're running on doesn't have enough "randomness" built in โ€” which normally shows up as strong_rand_bytes/1 raising error:low_entropy. so like, don't just do it for fun ๐Ÿ™ˆ

rand_uniform(Lo, Hi) -> N

Types:

Lo, Hi, N = integer()

Generates a random number N where Lo =< N < Hi. Uses the crypto library pseudo-random number generator. Hi has to be larger than Lo, obviously. ๐Ÿ’ซ

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

Same thing as application:start(crypto). that's it, that's the function ๐Ÿ’…

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

Same thing as application:stop(crypto). the reverse vibe ๐ŸŽ€

strong_rand_bytes(N :: integer() >= 0) -> binary()

Generates N bytes, randomly uniform over 0..255, and returns the whole thing in a binary. Uses a cryptographically secure prng that's seeded and periodically mixed with entropy straight from the operating system. By default that's the RAND_bytes method from OpenSSL. ๐Ÿ”ฅ

Might raise the exception error:low_entropy if the random generator failed because it didn't have enough secure "randomness". ๐Ÿ˜ญ

rand_seed() -> rand:state()

Creates a state object for random number generation so you can generate cryptographically strong random numbers (based on OpenSSL's BN_rand_range), and saves it in the process dictionary before returning it to you as well. See also rand:seed/1 and rand_seed_s/0. ๐Ÿ‘‘

When you use the state object from this function, the rand functions using it may raise the exception error:low_entropy if 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()

Creates a state object for random number generation so you can generate cryptographically strongly random numbers (based on OpenSSL's BN_rand_range). See also rand:seed_s/1. ๐ŸŒˆ

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

Note ๐Ÿ’ก โ€” The state you get back from this function cannot be used to get a reproducible random sequence like you can from the other rand functions, because reproducibility and cryptographically safe are literally not the same vibe, bestie. ๐Ÿซถ The only supported usage is to generate one distinct random sequence from this start state. that's the whole assignment.

rand_seed_alg(Alg) -> rand:state()

Types:

Alg = crypto | crypto_cache

Creates a state object for random number generation so you can generate cryptographically strong random numbers, and saves it in the process dictionary before returning it to you as well. See also rand:seed/1 and rand_seed_alg_s/1. โœจ

When you use the state object from this function, the rand functions using it may raise the exception error:low_entropy if 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()

Types:

Alg = crypto_aes

Creates a state object for random number generation so you can generate cryptographically unpredictable random numbers, and saves it in the process dictionary before returning it to you 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

look at that โ€” same seed, same numbers. that's the reproducible magic right there ๐Ÿช„

rand_seed_alg_s(Alg) -> rand:state()

Types:

Alg = crypto | crypto_cache

Creates a state object for random number generation so you can generate cryptographically strongly random numbers. See also rand:seed_s/1. ๐Ÿ’œ

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

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 the calculations fast on 64 bit machines. โšก

When you use the state object from this function, the rand functions using it may raise the exception error:low_entropy if 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 you're using the state object that this function hands you, the rand functions built on it might throw the exception low_entropy โ€” that's the vibe check failing when the random generator couldn't get enough secure "randomness" ๐Ÿ˜ญ

Note: the state that comes back from this function is not usable for getting a reproducible random sequence like you can from the other rand functions, because reproducibility doesn't match cryptographically safe ๐Ÿ’… Like, actually โ€” since random data gets cached, some numbers may get reproduced if you try, but it's unpredictable, so don't count on it ๐Ÿ™ˆ The only supported usage is generating one distinct random sequence from this start state. That's it. One. Periodt.

โœจ rand_seed_alg_s(Alg, Seed) -> rand:state() โœจ

Types:

Alg = crypto_aes

Bestie, this one creates a state object for random number generation so you can 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 then the generator states are scrambled through AES to create 58-bit pseudo random values ๐Ÿ”ฅ

The result should be statistically completely unpredictable random values โ€” the scrambling is cryptographically strong and the period is, and I quote, ridiculously long ๐ŸŒˆ But ngl 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 don't need the statistical quality of this function, there are faster algorithms in the rand module ๐Ÿฆ‹

Thanks to the generator it's using, the state object supports the rand:jump/0,1 function with distance 2^512 โœจ

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


โœจ ec_curves() -> [EllipticCurve] โœจ

Types:

EllipticCurve =
    ec_named_curve() | edwards_curve_dh() | edwards_curve_ed()

Use this to figure out which named elliptic curves are supported ๐Ÿ’–


โœจ ec_curve(CurveName) -> ExplicitCurve โœจ

Types:

CurveName = ec_named_curve()
ExplicitCurve = ec_explicit_curve()

Returns the defining parameters of an elliptic curve ๐ŸŒธ


โœจ sign(Algorithm, DigestType, Msg, Key) -> Signature โœจ

โœจ sign(Algorithm, DigestType, Msg, Key, Options) -> Signature โœจ

Types:

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

Uses the 3-tuple style for error handling, iykyk ๐Ÿ’…

Creates a digital signature ๐Ÿ”ฅ

The Msg is either the binary "cleartext" data to be signed, or it's 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 โœจ

โœจ verify(Algorithm, DigestType, Msg, Signature, Key, Options) -> Result โœจ

Types:

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

Also uses the 3-tuple style for error handling ๐Ÿ’…

Verifies a digital signature โœ…

The Msg is either the binary "cleartext" data to be signed, or it's 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 ๐ŸŒˆ

privkey_to_pubkey(Type, EnginePrivateKeyRef) โ†’ PublicKey

Types:

Type = rsa | dss
EnginePrivateKeyRef = engine_key_ref()
PublicKey = rsa_public() | dss_public()

Okay so this one reaches into an Engine, grabs the private key that's chillin' in there, and hands you back the matching public key ๐Ÿ’– The key has to actually be the kind you claim it is โ€” the Type parameter says which, and it's only rsa or dss, no mixing bestie.


engine_get_all_methods() โ†’ Result

Types:

Result = [engine_method_type()]

Returns a list of every single engine method that exists โœจ Like, the whole menu, not just what's on your plate.

Heads up babes: this may 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) โ†’ Result

Types:

EngineId = unicode:chardata()
PreCmds = PostCmds = [engine_cmnd()]
Result =
    {ok, Engine :: engine_ref()} | {error, Reason :: term()}

Loads the OpenSSL engine given by EngineId if it's available, and initializes it ๐ŸŒธ You get back ok and an engine handle; if the engine can't be loaded you get an error tuple instead, no cap.

It raises an error:badarg if the parameters are in wrong format ๐Ÿ™ˆ And 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

Types:

Engine = engine_ref()
Result = ok | {error, Reason :: term()}

Unloads the OpenSSL engine given by Engine ๐Ÿฆ‹ If the engine can't be unloaded, an error tuple comes back at you.

Raises error:badarg if the parameter's in wrong format. And yes, it may also raise 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

Types:

EngineId = unicode:chardata()
Result =
    {ok, Engine :: engine_ref()} | {error, Reason :: term()}

Gets you a reference to an engine that's already loaded, matched by EngineId ๐Ÿ”ฅ An error tuple is returned if the engine can't be unloaded โ€” yeah, that's literally what the docs say for this one, we're just reporting it faithfully, don't come for me ๐Ÿ˜ญ๐Ÿ’€

Raises error:badarg if the parameter's in wrong format. May also raise 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

Types:

Engine = term()
CmdName = CmdArg = unicode:chardata()
Result = ok | {error, Reason :: term()}

Sends ctrl commands to the OpenSSL engine given by Engine โญ This one is exactly the same as calling engine_ctrl_cmd_string/4 with Optional set to false โ€” same energy, shorter name, iykyk.

Raises error:badarg if the parameters are in wrong format. May also raise error:notsup in case there is no engine support in the underlying OpenSSL implementation.


engine_ctrl_cmd_string(Engine, CmdName, CmdArg, Optional) โ†’ Result

Types:

Engine = term()
CmdName = CmdArg = unicode:chardata()
Optional = boolean()
Result = ok | {error, Reason :: term()}

Sends ctrl commands to the OpenSSL engine given by Engine ๐Ÿงš Here's the tea on Optional, bestie: it's a boolean that can relax the semantics of the function ๐Ÿ‘€ If it's 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'll 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 ๐Ÿ’…

Raises error:badarg if the parameters are in wrong format. May also raise error:notsup in case there is no engine support in the underlying OpenSSL implementation.


engine_add(Engine) โ†’ Result

Types:

Engine = engine_ref()
Result = ok | {error, Reason :: term()}

Adds the engine to OpenSSL's internal list ๐Ÿ“‹ iconic, putting it on the roster.

Raises error:badarg if the parameters are in wrong format. May also raise error:notsup in case there is no engine support in the underlying OpenSSL implementation.


engine_remove(Engine) โ†’ Result

Types:

Engine = engine_ref()
Result = ok | {error, Reason :: term()}

Removes the engine from OpenSSL's internal list ๐Ÿซถ off the roster, bye bestie.

Raises error:badarg if the parameters are in wrong format. May also raise error:notsup in case there is no engine support in the underlying OpenSSL implementation.


engine_register(Engine, EngineMethods) โ†’ Result

Types:

Engine = engine_ref()
EngineMethods = [engine_method_type()]
Result = ok | {error, Reason :: term()}

Registers the engine to handle some type of methods โ€” for example engine_method_digests โœจ giving it a job, main character energy fr.

Raises error:badarg if the parameters are in wrong format. May also raise error:notsup in case there is no engine support in the underlying OpenSSL implementation.


engine_unregister(Engine, EngineMethods) โ†’ Result

Types:

Engine = engine_ref()
EngineMethods = [engine_method_type()]
Result = ok | {error, Reason :: term()}

Unregisters the engine so it don't handle some type of methods anymore ๐ŸŒˆ (yes, we're keeping the original grammar, it's part of the charm).

Raises error:badarg if the parameters are in wrong format. May also raise error:notsup in case there is no engine support in the underlying OpenSSL implementation.


engine_get_id(Engine) โ†’ EngineId

Types:

Engine = engine_ref()
EngineId = unicode:chardata()

Returns the ID for the engine โ€” or an empty binary if there's no id set ๐Ÿ˜ญ (everyone's had that phase).

Raises error:badarg if the parameters are in wrong format. May also raise error:notsup in case there is no engine support in the underlying OpenSSL implementation.


engine_get_name(Engine) โ†’ EngineName

Types:

Engine = engine_ref()
EngineName = unicode:chardata()

Returns the name (eg a description) for the engine, or an empty binary if there's no name set ๐ŸŽ€ a whole bio, or a blank one, no in-between.

Raises error:badarg if the parameters are in wrong format. May also raise error:notsup in case there is no engine support in the underlying OpenSSL implementation.


engine_list() โ†’ Result

Types:

Result = [EngineId :: unicode:chardata()]

Lists the id's of all engines in OpenSSL's internal list ๐Ÿ“ the whole group chat, laid out.

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. (Yes, it says it twice โ€” we don't skip lines around here ๐Ÿ’€)


ensure_engine_loaded(EngineId, LibPath) โ†’ Result

Types:

EngineId = LibPath = unicode:chardata()
Result =
    {ok, Engine :: engine_ref()} | {error, Reason :: term()}

Loads an engine given by EngineId, plus the path to the dynamic library implementing that engine ๐Ÿ”ฅ An error tuple is returned if the engine can't be loaded.

So here's how this one's different from the normal engine_load: it also adds the engine id to OpenSSL's internal engine list โœจ The difference between the first call and the following calls is that the first one loads the engine with the dynamical engine, and the following calls fetch it from OpenSSL's engine list. All references that get returned are equal โ€” same engine, same handle, periodt ๐Ÿ‘‘

Use the engine_unload/1 function to remove the references ๐Ÿ’… But remember: engine_unload/1 just removes the references to the engine, 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) โ€” don't be out here removing it repeatedly, bestie ๐Ÿ™ˆ

Raises error:badarg if the parameters are in wrong format. May also raise 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 ๐Ÿฆ‹


hash_equals(BinA, BinB) โ†’ Result

Types:

BinA = BinB = binary()
Result = boolean()

Constant time memory comparison for fixed length binaries โ€” think results of HMAC computations ๐Ÿ‘‘ This is the secure-comparison girlie, no early-exit side channels here, we love to see it.

Returns true if the binaries are identical, false if they are of the same length but not identical ๐Ÿซถ

๐Ÿšจ But listen: the function raises an error:badarg exception if the binaries are of different size. Like, not false โ€” an actual exception. So size-check first, or get rekt ๐Ÿ’€

pbkdf2_hmac(Digest, Pass, Salt, Iter, KeyLen) โ†’ Result

Types:

Digest = sha | sha224 | sha256 | sha384 | sha512
Pass = Salt = binary()
Iter = KeyLen = integer() >= 1
Result = binary()

Uses the 3-tuple style for error handling โœจ

This is PKCS #5 PBKDF2 (Password-Based Key Derivation Function 2) in combination with HMAC ๐ŸŒˆ stretching your password into a key, the classic, the iconic, the "please don't use it with a low Iter, I'm begging" situation ๐Ÿ’–


and that's the whole page, bestie!! ๐ŸŽ€โœจ you made it to the very end, so cute ๐Ÿซถ

This one was brought to you by Ericsson AB, running crypto 5.1.4.1, and documented under crypto(3erl) โ€” go forth and encrypt responsibly, mwah ๐Ÿ’…๐Ÿ’œ

๐Ÿ“ฆ where this page comes from