crypto

v5.9

Crypto Application

Description

The purpose of the Crypto application is to provide an Erlang API to cryptographic functions, see crypto. Note that the API is on a fairly low level and there are some corresponding API functions available in public_key, on a higher abstraction level, that uses the crypto application in its implementation.

DEPENDENCIES

The current crypto implementation uses nifs to interface OpenSSLs crypto library and may work with limited functionality with as old versions as OpenSSL 0.9.8c. FIPS mode support requires at least version 1.0.1 and a FIPS capable OpenSSL installation. We recommend using a version that is officially supported by the OpenSSL project. API compatible backends like LibreSSL should also work.

The crypto app is tested daily with at least one version of each of the OpenSSL 1.0.1, 1.0.2, 1.1.0, 1.1.1 and 3.0. FIPS mode is also tested for 1.0.1, 1.0.2 and 3.0.

Using OpenSSL 3.0 with Engines is supported since OTP 26.2.

Source releases of OpenSSL can be downloaded from the OpenSSL project home page, or mirror sites listed there.

CONFIGURATION

The following configuration parameters are defined for the crypto application. See app(3) for more information about configuration parameters.

fips_mode = boolean() - Specifies whether to run crypto in FIPS mode. This setting will take effect when the nif module is loaded. If FIPS mode is requested but not available at run time the nif module and thus the crypto module will fail to load. This mechanism prevents the accidental use of non-validated algorithms.

rand_cache_size = integer() - Sets the cache size in bytes to use by crypto:rand_seed_alg(crypto_cache) and crypto:rand_seed_alg_s(crypto_cache) . This parameter is read when a seed function is called, and then kept in generators state object. It has a rather small default value that causes reads of strong random bytes about once per hundred calls for a random value. The set value is rounded up to an integral number of words of the size these seed functions use.

Change

From Erlang/OTP 29, in interactive mode, application crypto will be automatically loaded if needed when module crypto is loaded. In embedded mode, module crypto will fail to load if application crypto has not been loaded by the boot script. This is all done to make sure crypto is not initialized with incorrect configuration parameters.

In Erlang/OTP 28 and earlier, no automatic loading of the application is done. If module crypto is then loaded (by a first call for example) before the application has been loaded, it will initialize with possibly incorrect configuration parameters. In particular, fips_mode will then default to false even if configured to be true.

SEE ALSO

application(3)

Crypto Release Notes

This document describes the changes made to the Crypto application.

Crypto 5.9

Fixed Bugs and Malfunctions

Fixed crypto:hash_equals/2 and FIPS when crypto is statically linked to the beam (with --enable-static-nifs and --disable-dynamic-ssl-lib).

Own Id: OTP-20025 Aux Id: PR-10817

Improvements and New Features

The rand:bytes/1 and rand:bytes_s/2 functions have been optimized by implementing a new internal callback function that crypto:rand_seed_alg/1 and crypto:alg_seed_alg_s/1 have been updated to use.

A new algorithm crypto_prng1, which also takes advantage of this new internal callback, has been added to crypto:rand_seed_alg/2 and crypto:rand_seed_alg_s/2. It is much faster then the existing crypto_aes, in particular for generating bytes.

Own Id: OTP-19882 Aux Id: OTP-19827, PR-10453

In interactive mode, application crypto is automatically loaded when the crypto module is loaded. This will ensure that the correct value of configuration parameter fips_mode is used to initialize OpenSSL if module crypto is called/loaded before the application crypto has been loaded. In embedded mode, module crypto will fail to load if the application has not been loaded.

Own Id: OTP-20035 Aux Id: PR-10830

OpenSSL engine support has been removed on Windows.

Own Id: OTP-20036 Aux Id: PR-10836

Added support for -unsafe attributes, which is used to mark functions as unsafe to use.

This is similar to but separate from deprecation, and the compiler will by default now generate warnings for calls to functions in Erlang/OTP that are known to be always unsafe.

Furthermore, xref can now be used to find calls to functions in another application that lack a -doc attribute (undocumented_function_calls), calls to functions in another application marked -doc false. (private_function_calls), as well as calls to unsafe functions (unsafe_function_calls).

Own Id: OTP-20066 Aux Id: PR-10839

The runtime system now supports generating encrypted crash dumps. See the description of --enable-encrypted-crash-dumps in Building and Installing Erlang/OTP.

Own Id: OTP-20085 Aux Id: PR-10993

Crypto 5.8.3

Fixed Bugs and Malfunctions

Fix memory leak in crypo:engine_load if called with incorrect commands.

Own Id: OTP-20014 Aux Id: PR-10798

Crypto 5.8.2

Fixed Bugs and Malfunctions

Fixed crypto:crypto_one_time_aead/4, which could crash the runtime system if invoked in parallel with the same state.

Own Id: OTP-19973 Aux Id: GH-10652, PR-10668

Crypto 5.8.1

Fixed Bugs and Malfunctions

Fixed static linking of OpenSSL 3.5+ on Windows.

Own Id: OTP-19993 Aux Id: PR-10732

Crypto 5.8

Fixed Bugs and Malfunctions

The deprecated function crypto:rand_uniform/2 has gotten a new replacement function crypto:strong_rand_range/1. When implementing this the documentation of crypto and rand has been rewritten a bit and improved.

Own Id: OTP-19841 Aux Id: PR-10344

Improvements and New Features

You can now build OTP with OpenSSL 3.5 or later on windows.

Own Id: OTP-19848

Added SLH-DSA algorithms for sign/verify. Twelve variants supported in total; all combinations of SHAKE or SHA2 hashing, with 128, 192 or 256 bits, and fast(f) or small(s).

Own Id: OTP-19856 Aux Id: PR-10268

Made crypto:generate_key(dh, [P, G, MaxPrivateKeyBitLength]) accept values of MaxPrivateKeyBitLength to be equal or larger than the bit length of P. If so, the maximum bit length is adjusted down to P's bit length minus one.

Own Id: OTP-19872 Aux Id: PR-10394

Crypto 5.7

Fixed Bugs and Malfunctions

NIFs and linked-in drivers are now loadable when running in an Erlang source tree on Windows.

Own Id: OTP-19686 Aux Id: PR-9969

Fixed bug seen to cause beam crash when doing init:restart() with crypto statically linked to OpenSSL (--disable-dynamic-ssl-lib). Bug exists since OTP 28.0.

Own Id: OTP-19721 Aux Id: GH-10061, PR-10076

Fixed crypto:strong_rand_bytes failing after init:restart on MacOS with statically linked OpenSSL.

Own Id: OTP-19725 Aux Id: GH-10079, PR-10085

Fixed crypto:hash(shake128 | shake256) for OpenSSL 3.4 and newer.

Own Id: OTP-19733 Aux Id: GH-9901, PR-9982

Rendering of some tables in the documentation has been improved.

Own Id: OTP-19752 Aux Id: PR-10142

Improvements and New Features

Support for ML-DSA and ML-KEM provided by OpenSSL 3.5.

Algorithms mldsa44, mldsa65 and mldsa87 can be passed to crypto:sign/4 and crypto:verify/5.

New functions crypto:encapsulate_key/2 and crypto:decapsulate_key/3 can be used with mlkem512, mlkem768 and mlkem1024 to safely generate and communicate an encapsulated shared secret.

Own Id: OTP-19657 Aux Id: PR-9900

Added support for SHA2 512/224 and SHA2 512/256 truncated hashes.

Own Id: OTP-19666 Aux Id: PR-9721

Crypto 5.6

Fixed Bugs and Malfunctions

Fixed minor potential leak of EVP_MAC when crypto module is unloaded.

Own Id: OTP-19500 Aux Id: PR-9119

Added copyright and license to crypto_ec_curves.erl

Own Id: OTP-19554

Improvements and New Features

The crypto:start/0, crypto:stop/0, and crypto:enable_fips_mode/1 functions have been deprecated.

Own Id: OTP-19155 Aux Id: PR-8592

Warnings are now logged if module crypto with FIPS-supported OpenSSL is loaded without application crypto being loaded. In this case FIPS will be disabled even if the user had set application parameter fips_mode.

Own Id: OTP-19156 Aux Id: PR-8590

The functionality of crypto:crypto_one_time_aead/6 is now also available in the new functions crypto:crypto_one_time_aead_init/4 and crypto:crypto_one_time_aead/4, which makes it possible to reuse initialization.

Own Id: OTP-19426 Aux Id: PR-9289

Added support for compiling Erlang/OTP for Windows on ARM64.

Own Id: OTP-19480 Aux Id: PR-8734

New key fips_provider_buildinfo in map returned by crypto:info/0. If present, it contains the version of the FIPS provider which may be different than the version of the rest of OpenSSL.

Own Id: OTP-19487 Aux Id: GH-9366, PR-9410

Exported crypto types sha3(), hmac_hash_algorithm() and cmac_cipher_algorithm().

Own Id: OTP-19510 Aux Id: PR-9448

When compiling C/C++ code on Unix systems, the compiler hardening flags suggested by the Open Source Security Foundation are now enabled by default. To disable them, pass --disable-security-hardening-flags to configure.

Own Id: OTP-19519 Aux Id: PR-9441

The license and copyright header has changed format to include an SPDX-License-Identifier. At the same time, most files have been updated to follow a uniform standard for license headers.

Own Id: OTP-19575 Aux Id: PR-9670

Crypto 5.5.3.2

Fixed Bugs and Malfunctions

Fixed bug that could cause runtime crash after ~2 billion calls to crypto:mac_init due to a double EVP_MAC_free.

Own Id: OTP-20041 Aux Id: PR-10859

Crypto 5.5.3.1

Fixed Bugs and Malfunctions

Fixed static linking of OpenSSL 3.5+ on Windows.

Own Id: OTP-19993 Aux Id: PR-10732

Crypto 5.5.3

Fixed Bugs and Malfunctions

crypto will now work when ED25519 and X25519 are available while ED448 and X448 are not, which is the case in LibreSSL. This is necessary for supporting TLS1.3 using LibreSSL.

Own Id: OTP-19399 Aux Id: GH-9000, PR-9136

Crypto 5.5.2

Fixed Bugs and Malfunctions

crypto:strong_rand_bytes/2 fixed to work on Ubuntu pro with installed FIPS support.

Own Id: OTP-19223 Aux Id: PR-8800, GH-8769

Fixed crypto:hash_final/1 for digest types shake128 and shake256 when using OpenSSL 3.4 or newer.

Own Id: OTP-19329 Aux Id: GH-8997, PR-9002

Crypto 5.5.1

Fixed Bugs and Malfunctions

crypto built with --enable-fips will now accept an OpenSSL 3 lib without fips provider as long as fips mode is not enabled.

Own Id: OTP-19212 Aux Id: GH-8562

Improvements and New Features

Added a warning in the documentation to avoid calling crypto:start/0 as it does not work for FIPS mode. Use application:start(crypto) instead.

Own Id: OTP-19143

Deprecation of RSA encryption functions has been reverted, as there still exists legitimate use cases with other padding modes than PKCS-1.

While use PCKS-1 padding with some versions of cryptolib could be considered secure, we still recommend using other algorithms that are less sensitive to oracle attacks.

Own Id: OTP-19163

Compiler warnings for some removed functions have been corrected to point out the correct replacement functions.

Own Id: OTP-19186 Aux Id: PR-8709

Crypto 5.5

Improvements and New Features

The documentation has been migrated to use Markdown and ExDoc.

Own Id: OTP-18955 Aux Id: PR-8026

Removed functions crypto_dyn_iv_init/3 and crypto_dyn_iv_update/3 which were marked as deprecated since OTP 25.

Own Id: OTP-18973

Add support for sm3 hash and hmac.

Own Id: OTP-18975 Aux Id: PR-6658

OPENSSL_thread_stop is called when crypto is purged to not leak thread specific data.

Own Id: OTP-18978 Aux Id: PR-7809

Add SM4 block cipher implemented according to GB/T 32907-2016.

Own Id: OTP-19005 Aux Id: PR-8168

The existing function ssl:key_exporter_materials/4 is now documented and supported.

POTENTIAL INCOMPATIBILITY

Own Id: OTP-19016 Aux Id: PR-8233

Due to another attack on PKCS #1 v1.5 padding, known as the Marvin attack, about which we were alerted by Hubert Kario from Red Hat. You can find more details about the attack at https://people.redhat.com/~hkario/marvin/ Functions that may be vulnerable are now deprecated.

Note that you might mitigate the problem by using appropriate versions of OpenSSL together with our software, but we recommend not using them at all.

Also avoid using TLS versions prior to TLS-1.2 (not supported by default) and do not enable RSA-key exchange cipher suites (not supported by default).

POTENTIAL INCOMPATIBILITY

Own Id: OTP-19075

Crypto 5.4.2.4

Fixed Bugs and Malfunctions

Fixed static linking of OpenSSL 3.5+ on Windows.

Own Id: OTP-19993 Aux Id: PR-10732

Crypto 5.4.2.3

Fixed Bugs and Malfunctions

Fixed bug that could cause blocking scheduler threads in crypto:supports(curves) if called the first time by more than one Erlang process. Bug exists only in OTP-26.2.5.4.

Own Id: OTP-19316 Aux Id: GH-8971, PR-8979

Fixed crypto:hash_final/1 for digest types shake128 and shake256 when using OpenSSL 3.4 or newer.

Own Id: OTP-19329 Aux Id: GH-8997, PR-9002

Crypto 5.4.2.2

Fixed Bugs and Malfunctions

crypto built with --enable-fips will now accept an OpenSSL 3 lib without fips provider as long as fips mode is not enabled.

Own Id: OTP-19212 Aux Id: GH-8562, PR-8762

crypto:strong_rand_bytes/2 fixed to work on Ubuntu pro with installed FIPS support.

Own Id: OTP-19223 Aux Id: PR-8800, GH-8769

Crypto 5.4.2.1

Improvements and New Features

Add warning in documentation to avoid crypto:start/0 as it does not work for FIPS mode. Use application:start(crypto) instead.

Own Id: OTP-19143

Crypto 5.4.2

Fixed Bugs and Malfunctions

Fix building with --enable-fips with OpenSSL 3 on MacOS.

Own Id: OTP-19038 Aux Id: GH-8271, PR-8277

Crypto 5.4.1

Fixed Bugs and Malfunctions

Fix compile error when OPENSSL_NO_DES is defined.

Own Id: OTP-18921

The function crypto:pbkdf2_hmac will no longer block the main schedulers. If the iteration count or block size parameters are such that the function is likely to take a long time to execute, the function will be scheduled to run on a dirty CPU scheduler.

Own Id: OTP-18996 Aux Id: PR-8173, PR-8174

Crypto 5.4

Fixed Bugs and Malfunctions

Fixed some benign compile warnings on Windows.

Own Id: OTP-18895

Improvements and New Features

Enable engine support for OpenSSL versions 3.

Own Id: OTP-18832 Aux Id: PR-7763

Crypto 5.3

Fixed Bugs and Malfunctions

Fix VM crash caused by crypto being purged and reloaded (by init:restart for example) on OS with musl libc (such as Alpine linux).

Own Id: OTP-18670 Aux Id: GH-7436, PR-7450

Improved understanding of LibreSSL versions. Support chacha20 and chacha20_poly1305 for LibreSSL 3.7. Reflect removal of support for the DSS/DSA algorithm which was done in LibreSSL 2.6.1.

Own Id: OTP-18758 Aux Id: PR-7209

Improvements and New Features

FIPS supported by crypto for OpenSSL 3.0. and 3.1..

Own Id: OTP-18666 Aux Id: PR-7392

Crypto 5.2

Fixed Bugs and Malfunctions

Fix cmac_update aes_128_cbc for LibreSSL.

Own Id: OTP-18571

Improvements and New Features

Add support for SHAKE128 and SHAKE256.

Own Id: OTP-18204 Aux Id: PR-6203

Make the -DOPENSSL_API_COMPAT flag work without warnings.

Own Id: OTP-18206 Aux Id: PR-6167

Replace size/1 with either tuple_size/1 or byte_size/1

The size/1 BIF is not optimized by the JIT, and its use can result in worse types for Dialyzer.

When one knows that the value being tested must be a tuple, tuple_size/1 should always be preferred.

When one knows that the value being tested must be a binary, byte_size/1 should be preferred. However, byte_size/1 also accepts a bitstring (rounding up size to a whole number of bytes), so one must make sure that the call to byte_size/ is preceded by a call to is_binary/1 to ensure that bitstrings are rejected. Note that the compiler removes redundant calls to is_binary/1, so if one is not sure whether previous code had made sure that the argument is a binary, it does not harm to add an is_binary/1 test immediately before the call to byte_size/1.

Own Id: OTP-18405 Aux Id: GH-6672,PR-6702,PR-6768,PR-6700,PR-6769,PR-6812,PR-6814

Handling of on_load modules during boot has been improved by adding an extra step in the boot order for embedded mode that runs all on_load handlers, instead of relying on explicit invocation of them, later, when the kernel supervision tree starts.

This is mostly a code improvement and OTP internal simplification to avoid future bugs and to simplify code maintenance.

Own Id: OTP-18447

Crypto 5.1.4.3

Fixed Bugs and Malfunctions

Fix building with --enable-fips with OpenSSL 3 on MacOS.

Own Id: OTP-19038 Aux Id: GH-8271, PR-8277

Crypto 5.1.4.2

Fixed Bugs and Malfunctions

The function crypto:pbkdf2_hmac will no longer block the main schedulers. If the iteration count or block size parameters are such that the function is likely to take a long time to execute, the function will be scheduled to run on a dirty CPU scheduler.

Own Id: OTP-18996 Aux Id: PR-8173, PR-8174

Crypto 5.1.4.1

Fixed Bugs and Malfunctions

Fix VM crash caused by crypto being purged and reloaded (by init:restart for example) on OS with musl libc (such as Alpine linux).

Own Id: OTP-18670 Aux Id: GH-7436, PR-7450

Crypto 5.1.4

Fixed Bugs and Malfunctions

With this change, random errors are fixed for crypto:generate_key calls with OpenSSL 3.

Own Id: OTP-18555

Crypto 5.1.3

Fixed Bugs and Malfunctions

A user defined runtime library path configured using --with-ssl-rpath=<PATHS> could fail to be enabled.

Own Id: OTP-18384 Aux Id: PR-6596

Ensure that configure fails if a user defined runtime library path has been passed by the user, but cannot set.

Own Id: OTP-18408

Crypto 5.1.2

Fixed Bugs and Malfunctions

Fix configure with --with-ssl and --disable-dynamic-ssl-lib on Windows.

Own Id: OTP-18147 Aux Id: GH-6024, PR-6056

Remove all references correctly in the garbage collection if an engine handle was not explicit unloaded.

Own Id: OTP-18152

Changed the behaviour of the engine load/unload functions

The engine load/unload functions have got changed semantics to get a more consistent behaviour and work correct when variables are garbage collected.

The load functions now don't register the methods for the engine to replace. That will now be handled with the new functions engine_register/engine_unregister if needed.

Some functions are removed from the documentation and therefor the API, but they are left in the code for compatibility.

engine_load/4: is now the same as engine_load/3

engine_unload/2: is now the same as engine_unload/1

ensure_engine_loaded/3: is now the same as ensure_engine_loaded/2

ensure_engine_unloaded/1, ensure_engine_unloaded/2: is now the same as engine_unload/1

* POTENTIAL INCOMPATIBILITY *

Own Id: OTP-18172 Aux Id: ERIERL-826

Fixed a naming bug for AES-CFB and Blowfish-CFB/OFB when linked with OpenSSL 3.0 cryptolib.

Own Id: OTP-18200

Sign/verify does now behave as in OTP-24 and earlier for eddsa.

Own Id: OTP-18205 Aux Id: GH-6219

Improvements and New Features

Pass elliptic curve names from crypto.erl to crypto's nif.

Own Id: OTP-18037

The configure option --disable-deprecated-warnings is removed. It was used for some releases when the support for OpenSSL 3.0 was not completed. It is not needed in OTP 25.

Own Id: OTP-18133

Crypto is now considered to be usable with the OpenSSL 3.0 cryptolib for production code.

ENGINE and FIPS are not yet fully functional.

Own Id: OTP-18153

Do not exit if the legacy provider is missing in libcrypto 3.0.

Own Id: OTP-18217

Crypto 5.1.1

Fixed Bugs and Malfunctions

Note in the documentation that MODP (rfc3526) groups and OpenSSL 3.0 can give an error if a call to crypto:generate_key/2 specifies a key length, and that length is to small.

Own Id: OTP-18046

Improvements and New Features

The cmac now uses only the 3.0 API

Own Id: OTP-18010

Documentation is now updated with which OpenSSL cryptolib versions that OTP currently is tested.

Own Id: OTP-18132

Crypto 5.1

Fixed Bugs and Malfunctions

Fix timing bug in ensure_engine_loaded

When two ensure_engine_loaded() calls were done in parallel there was a possibility that a crypto lib function was called by both instead of just one of them which resulted in an error. This is solved by moving the implementation from erlang down into a NIF function that uses a mutex to protect the sensitive part.

Own Id: OTP-17858 Aux Id: ERIERL-728

Remove faulty types run_time_error() and descriptive_error().

Own Id: OTP-17984

Improvements and New Features

Input for configure scripts adapted to autoconf 2.71.

Own Id: OTP-17414 Aux Id: PR-4967

Add crypto:hash_equals/2

Own Id: OTP-17471 Aux Id: PR-4750

Add /opt/homebrew/opt/openssl to standard locations to search for OpenSSL cryptolib.

Own Id: OTP-17561

crypto_dyn_iv_init/3 and crypto_dyn_iv_update/3 are deprecated.

Own Id: OTP-17870

The information in error messages are increased.

Previously the error was signaled with en error class exception badarg, notsup or error, and also in some more ways like an other exception or a return value in a non-standardized format.

Now it is an error-class exception {notsup|badarg|error, InfoFromCfile, Description::string()}.

The InfoFromCfile is a term with name and line number of the C-file where the error was found. This is primarily intended for a crypto maintainer or an advanced user to find the cause of complicated errors - maybe in crypto itself. The contents of that term might be changed in the future.

The Description is a clear text string that describes the error. In case of badarg and notsup the intention is that it should help the user to find the cause ("Bad key size" as an example). Specially for some error that are unlikely, the string may not be possible to understand without deep knowledge of the underlying cryptolib. Such messages are intended for a crypto maintainer.

The first element on call stack (the S in try ... catch error:E:S .... end) gives more information like the actual argument list in the call of crypto and the argument number (if possible) in the call to the NIF inside crypto.

The functions in crypto affected by this change are:

sign/4, sign/5, verify/5, verify/6,

generate_key/2, generate_key/3, compute_key/4,

hash/2, hash/4, hash_init/1, hash_update/4, hash_final/1,

mac/3,4, mac_init/3, mac_update/2, mac_final/2,

pbkdf2_hmac/5,

public_encrypt/4, private_decrypt/4, private_encrypt/4, public_decrypt/4

This schema was introduced earlier in:

crypto_init/3, crypto_init/4, crypto_update/2, crypto_final/1, crypto_get_data/1,

crypto_one_time/4, crypto_one_time/5, crypto_one_time_aead/6, crypto_one_time_aead/7

* POTENTIAL INCOMPATIBILITY *

Own Id: OTP-17965

Add Output Feedback mode (OFB) support for AES encryption / decryption for key sizes of 128, 192 and 256 bits.

Own Id: OTP-18067 Aux Id: PR-5866

The cryptolib API deprecated in OpenSSL 3.0 is now no longer used with a few exceptions listed below.

Although OpenSSL 3.0.x itself is stable, its usage in OTP/crypto should still not be considered suitable for production code.

The use of ENGINEs is still disabled by default when using 3.0.

Deprecated functions are still called in the otp_test_engine.c (only used in tests), in mac.c (EVP_PKEY_new_CMAC_key) and five function calls in ec.c (EVP_PKEY_assign, EC_KEY_get_conv_form, EVP_PKEY_get1_EC_KEY, EC_KEY_get0_group and EC_KEY_set_public_key).

Own Id: OTP-18086 Aux Id: OTP-16282, OTP-16643, OTP-16644, OTP-17701, OTP-17702, OTP-17704

Crypto 5.0.6.5

Fixed Bugs and Malfunctions

The function crypto:pbkdf2_hmac will no longer block the main schedulers. If the iteration count or block size parameters are such that the function is likely to take a long time to execute, the function will be scheduled to run on a dirty CPU scheduler.

Own Id: OTP-18996 Aux Id: PR-8173, PR-8174

Crypto 5.0.6.4

Fixed Bugs and Malfunctions

Fix VM crash caused by crypto being purged and reloaded (by init:restart for example) on OS with musl libc (such as Alpine linux).

Own Id: OTP-18670 Aux Id: GH-7436, PR-7450

Crypto 5.0.6.3

Fixed Bugs and Malfunctions

Changed the behaviour of the engine load/unload functions

The engine load/unload functions have got changed semantics to get a more consistent behaviour and work correct when variables are garbage collected.

The load functions now don't register the methods for the engine to replace. That will now be handled with the new functions engine_register/engine_unregister if needed.

Some functions functions are removed from the documentation and therefor the API, but they are left in the code for compatibility.

engine_load/4: is now the same as engine_load/3

engine_unload/2: is now the same as engine_unload/1

ensure_engine_loaded/3: is now the same as ensure_engine_loaded/2

ensure_engine_unloaded/1, ensure_engine_unloaded/2: is now the same as engine_unload/1

* POTENTIAL INCOMPATIBILITY *

Own Id: OTP-18172 Aux Id: ERIERL-826

Crypto 5.0.6.2

Fixed Bugs and Malfunctions

Fix configure with --with-ssl and --disable-dynamic-ssl-lib on Windows.

Own Id: OTP-18147 Aux Id: GH-6024, PR-6056

Crypto 5.0.6.1

Fixed Bugs and Malfunctions

Fix timing bug in ensure_engine_loaded

When two ensure_engine_loaded() calls were done in parallel there was a possibility that a crypto lib function was called by both instead of just one of them which resulted in an error. This is solved by moving the implementation from erlang down into a NIF function that uses a mutex to protect the sensitive part.

Own Id: OTP-17858 Aux Id: ERIERL-728

Crypto 5.0.6

Improvements and New Features

The crypto app in OTP can since OTP-24.2 be compiled, linked and used with the new OpenSSL 3.0 cryptolib.

The crypto app has 3.0 support has been improved, but is still **not recommended** for other usages than experiments and alpha testing. There are not yet any guaranties that it works, not even together with other OTP applications like for example SSL and SSH, although there are no known errors.

Since the previous release, OTP-24.2, the following improvements have been done:

- It has been tested during nearly every nightly test on the OTP lab

- The hash algorithms md4 and ripemd160 have been enabled with OpenSSL 3.0.

- The ciphers blowfish_cbc, blowfish_ecb, des_cbc, des_cfb, des_ecb, rc2_cbc and rc4 have been enabled with OpenSSL 3.0.

Disabled or unsupported with OpenSSL 3.0 are still:

- ENGINE support

- FIPS mode

- Other providers than the built-in ones

- Compiling and linking with OpenSSL 3.0 cryptolib in compatibility modes (for example to behave as 1.1.1)

and, the ciphers blowfish_cfb64 and blowfish_ofb64 are not supported and will not be either.

Deprecated functions in the OpenSSL 3.0 cryptolib must not be disabled as OTP/crypto still uses some of the deprecated API functions. The gcc flag -Wno-deprecated-declarations is set to prevent deprecation warnings to be printed when compiling.

Own Id: OTP-17812 Aux Id: OTP-16646, OTP-16282

Crypto is adapted to LibreSSL 3.5.0 on OpenBSD.

Own Id: OTP-17941 Aux Id: OTP-17942

New configure option ( --disable-otp-test-engine) to prohibit the build of the OTP test engine used in some test suites.

The reason is that the test engine could be hard to compile on for instance LibreSSL 3.5.0. For that particular cryptolib version (or higher), this configure option is set automatically.

Own Id: OTP-17942 Aux Id: OTP-17941

Crypto 5.0.5

Fixed Bugs and Malfunctions

Fixed the C-warning "implicit declaration of function 'OpenSSL_version_num'" if compiling with an early LibreSSL version.

Own Id: OTP-17637

FIPS availability was not checked correctly for AEAD ciphers.

Own Id: OTP-17740

Fixed that cipher aliases (like aes_cbc etc) could be present even if the aliased cipher(s) (like aes_128_cbc, aes_256_cbc,... etc) was missing.

Own Id: OTP-17741

Improvements and New Features

The crypto app in OTP can now be compiled, linked and used with the new OpenSSL 3.0 cryptolib.

It has not yet been extensively tested and is in this release **not recommended** for other usages than experiments and alpha testing. There are not yet any guaranties that it works, not even together with other OTP applications like for example SSL and SSH, although there are no known errors.

Compiling and linking with OpenSSL 3.0 cryptolib in compatibility modes (for example to behave as 1.1.1) are not tested. It is not tested with external providers.

The support for FIPS mode does not yet work, and is disabled when compiled with OpenSSL 3.0.

Deprecated functions in the OpenSSL 3.0 cryptolib must not be disabled as OTP/crypto still uses some of the deprecated API functions. The gcc flag -Wno-deprecated-declarations is set to prevent deprecation warnings to be printed when compiling.

The hash algorithms md4 and ripemd160 are disabled temporarily when compiled with OpenSSL 3.0.

The ciphers blowfish_cbc, blowfish_cfb64, blowfish_ecb, blowfish_ofb64, des_cbc, des_cfb, des_ecb, rc2_cbc and rc4 are disabled temporarily when compiled with OpenSSL 3.0.

Own Id: OTP-16646 Aux Id: OTP-16282

The error handling in crypto is partly refactored using the new error reporting support. Errors earlier propagated like exceptions are still so, but when the failing function is called from the terminal - for example during failure hunting - a more descriptive text is produced.

Own Id: OTP-17241

A new function crypto:info/0 which presents some data about the compilation and linkage of the crypto nif is added.

Own Id: OTP-17603

Added the pbkdf2_hmac/5 function to the crypto module.

It calls the PKCS5_PBKDF2_HMAC function which implements PBKD2 with HMAC in an efficient way.

Own Id: OTP-17808 Aux Id: PR-5421

Crypto 5.0.4

Fixed Bugs and Malfunctions

Fixed minor memory leak at crypto module purge.

Own Id: OTP-17668 Aux Id: PR-5245

Fix possible inconsistency in fips mode when linking with some cryptolibs.

Own Id: OTP-17672

Crypto 5.0.3

Fixed Bugs and Malfunctions

Fix bug in crypto:ensure_engine_unloaded. Also fixed minor memory leak related to engine unloading.

Own Id: OTP-17593 Aux Id: ERIERL-679

Fixes that FIPS enable and disable (or vice versa) on Windows sometimes leads to core dump at the time of process exit.

Own Id: OTP-17618 Aux Id: PR-5126, GH-4920

Improvements and New Features

Disable fips if cryptolib < 1.0.1 and OTP/crypto is configured with --enable-fips

If not, there could be compiling or loading problems with antique OpenSSL versions.

Own Id: OTP-17389

Crypto 5.0.2

Fixed Bugs and Malfunctions

EC keys are now zero-padded to the expected length if needed.

Own Id: OTP-17442 Aux Id: GH-4861

Crypto 5.0.1

Fixed Bugs and Malfunctions

Removed a risk for coredump.

Own Id: OTP-17391 Aux Id: GH-4810

Fixed and documented the DED_LDFLAGS_CONFTEST configuration variable in $ERL_TOP/HOWTO/INSTALL.md.

Own Id: OTP-17419 Aux Id: GH-4821

Commit of generated configure script.

Own Id: OTP-17420 Aux Id: OTP-17398, GH-4821

Crypto 5.0

Fixed Bugs and Malfunctions

Add /usr/local/opt/openssl to the openssl configure search path. This path is where some tools on OS X place openssl.

Own Id: OTP-16882

Fix compiler warnings produced by the clang compiler.

Own Id: OTP-17105 Aux Id: PR-2872

The configure scripts in crypto and erts now fail if a requested feature cannot be enabled.

Large parts of the configure script of crypto have been rewritten with various improvements and bug fixes. It is now better at finding usable OpenSSL libraries, but will in the following cases fail to detect OpenSSL libraries where it previously sometimes detected the libraries by chance:

OpenSSL installations with include directory and lib directory parts installed in different base directories. In order to detect such installations after this change, the user must explicitly specify the locations using the --with-ssl=<path> and the --with-ssl-incl=<path> configure command line arguments.

When building with old gcc compilers or other compilers on Debian derivatives with multiarch directories under the lib directory. In order to detect such installations after this change, the user must explicitly specify the multiarch directory name using the --with-ssl-lib-subdir=lib/<multiarch-dir> configure command line argument.

Own Id: OTP-17254 Aux Id: ERIERL-618, GH-4230

The value 'none' was missing in the specs of crypto:sign/4 and crypto:verify/6.

Own Id: OTP-17312 Aux Id: PR-4723

Improvements and New Features

The functions and cipher names that were deprecated in OTP-23.0 are now removed.

* POTENTIAL INCOMPATIBILITY *

Own Id: OTP-16656

Removed installed directory priv/obj/ containing superfluous object files.

Own Id: OTP-17001 Aux Id: PR-2852

TLS connections now support EdDSA certificates.

Own Id: OTP-17142 Aux Id: PR-4756, GH-4637, GH-4650

Add prop_aead attribute to map from crypto:cipher_info/1.

Own Id: OTP-17313 Aux Id: PR-4686

Crypto 4.9.0.4

Fixed Bugs and Malfunctions

Changed the behaviour of the engine load/unload functions

The engine load/unload functions have got changed semantics to get a more consistent behaviour and work correct when variables are garbage collected.

The load functions now don't register the methods for the engine to replace. That will now be handled with the new functions engine_register/engine_unregister if needed.

Some functions functions are removed from the documentation and therefor the API, but they are left in the code for compatibility.

engine_load/4: is now the same as engine_load/3

engine_unload/2: is now the same as engine_unload/1

ensure_engine_loaded/3: is now the same as ensure_engine_loaded/2

ensure_engine_unloaded/1, ensure_engine_unloaded/2: is now the same as engine_unload/1

* POTENTIAL INCOMPATIBILITY *

Own Id: OTP-18172 Aux Id: ERIERL-826

Crypto 4.9.0.3

Fixed Bugs and Malfunctions

Fix timing bug in ensure_engine_loaded

When two ensure_engine_loaded() calls were done in parallel there was a possibility that a crypto lib function was called by both instead of just one of them which resulted in an error. This is solved by moving the implementation from erlang down into a NIF function that uses a mutex to protect the sensitive part.

Own Id: OTP-17858 Aux Id: ERIERL-728

Remove all references correctly in the garbage collection if an engine handle was not explicit unloaded.

Own Id: OTP-18152

Crypto 4.9.0.2

Fixed Bugs and Malfunctions

EC keys are now zero-padded to the expected length if needed.

Own Id: OTP-17442 Aux Id: GH-4861

Crypto 4.9.0.1

Fixed Bugs and Malfunctions

Removed a risk for coredump.

Own Id: OTP-17391 Aux Id: GH-4810

Commit of generated configure script.

Own Id: OTP-17420 Aux Id: OTP-17398, GH-4821

Crypto 4.9

Fixed Bugs and Malfunctions

Fix minor memory leaks in crypto ENGINE and robustify the code.

Own Id: OTP-17212

The otp_test_engine no longer fails if NO_EC* is set in the OpenSSL configuration.

Own Id: OTP-17256 Aux Id: PR-4580, GH-4573

Improvements and New Features

Various address sanitizer support.

Own Id: OTP-16959 Aux Id: PR-2965

EVP is now disabled for OpenSSL cryptolib versions up to and including 1.0.2

Own Id: OTP-17116 Aux Id: PR-2972

Warning for unused C function removed

Own Id: OTP-17145 Aux Id: OTP-17105, PR-2872

Crypto 4.8.3

Fixed Bugs and Malfunctions

Adding missing flag in BN-calls in SRP.

Own Id: OTP-17107

Crypto 4.8.2

Fixed Bugs and Malfunctions

Fixed usage of AC_CONFIG_AUX_DIRS() macros in configure script sources.

Own Id: OTP-17093 Aux Id: ERL-1447, PR-2948

Crypto 4.8.1

Fixed Bugs and Malfunctions

Build the supported curves cache in the NIF when crypto is loaded, no matter how it is loaded.

This prevents a possible problem with different processes starting the crypto application concurrently.

Own Id: OTP-16819 Aux Id: PR-2720

It is now possible to build with crypto and openssl gprof-enabled and statically link them into the VM.

Own Id: OTP-17029

Improvements and New Features

Fixed performance loss in HMAC when using older OpenSSL due to mutex issues.

A workaround is implemented to allow fallback from using the EVP API for HMAC operations. On some architectures this may improve the performance, especially with old OpenSSL versions. This fallback to low-level functions is always enabled for openssl versions before 1.0.2.

Own Id: OTP-17025 Aux Id: ERL-1400, PR-2877

Crypto 4.8

Fixed Bugs and Malfunctions

Fix type spec bug in crypto for crypto_init and crypto:one_time

Own Id: OTP-16658 Aux Id: OTP-15884, ERL-1257

The deprecation message for crypto:rand_uniform/2 indicated a non-existent function. The correct one (rand:uniform/1) is now suggested.

Own Id: OTP-16846 Aux Id: PR-2741

Improvements and New Features

Implemented a workaround to allow fallback from using the EVP API for Diffie-Hellman key generation

Own Id: OTP-16771 Aux Id: ERIERL-509

The internal Diffie-Hellman high level API for key generation was slow in old and by OpenSSL now unsupported cryptolib versions (1.0.1 and earlier).

If such a cryptolib is used anyhow, the low-level API is used internally in the crypto application.

Own Id: OTP-16774

Crypto 4.7

Fixed Bugs and Malfunctions

Crypto reported unsupported elliptic curves as supported on e.g Fedora distros.

Own Id: OTP-16579 Aux Id: ERL-825

Improvements and New Features

Support for ed25519 and ed448 added to crypto:generate_key.

Own Id: OTP-15967 Aux Id: PR-2329

The new crypto functions api (crypto_init, crypto_update and crypto_one_time) has been updated.

There is now a function crypto_final/1 and a possibility to set options in crypto_init/3 and crypto_init/4. See the manual for details.

Own Id: OTP-16160

As announced in OTP 22.0, a New API was introduced in CRYPTO. See the New and Old API chapter in the CRYPTO User's Guide for more information and suggested replacement functions.

The Old API is now deprecated in OTP-23.0 and will be removed in OTP-24.0.

This deprecation includes cipher names. See the section Retired cipher names in the crypto User's Guide, chapter The Old API.

Own Id: OTP-16232

Fix C-compilation without deprecated OpenSSL cryptolib APIs

Own Id: OTP-16369 Aux Id: PR-2474

Refactored the internal handling of deprecated and removed functions.

Own Id: OTP-16469

Added missing 'eddh' to crypto:supports(public_keys).

Own Id: OTP-16583

Crypto 4.6.5.4

Fixed Bugs and Malfunctions

EC keys are now zero-padded to the expected length if needed.

Own Id: OTP-17442 Aux Id: GH-4861

Crypto 4.6.5.3

Fixed Bugs and Malfunctions

Removed a risk for coredump.

Own Id: OTP-17391 Aux Id: GH-4810

Commit of generated configure script.

Own Id: OTP-17420 Aux Id: OTP-17398, GH-4821

Crypto 4.6.5.2

Fixed Bugs and Malfunctions

Adding missing flag in BN-calls in SRP.

Own Id: OTP-17107

Crypto 4.6.5.1

Improvements and New Features

Implemented a workaround to allow fallback from using the EVP API for Diffie-Hellman key generation

Own Id: OTP-16771 Aux Id: ERIERL-509

Crypto 4.6.5

Fixed Bugs and Malfunctions

Fixed potential memory leaks involving calls to the crypto ng_api.

Own Id: OTP-16428 Aux Id: PR-2511

Crypto 4.6.4

Fixed Bugs and Malfunctions

Constant time comparisons added.

Own Id: OTP-16376

Crypto 4.6.3

Improvements and New Features

The ciphers aes_cfb8 and aes_cfb128 are now using the EVP interface. The supported key lengths are 128, 192 and 256 bits.

Own Id: OTP-16133 Aux Id: PR-2407

The ciphers aes_cfb8 and aes_cfb128 are now available in FIPS enabled mode.

Own Id: OTP-16134 Aux Id: PR-2407

Crypto 4.6.2

Fixed Bugs and Malfunctions

The AEAD tag was not previously checked on decrypt with chacha20_poly1305

Own Id: OTP-16242 Aux Id: ERL-1078

Crypto 4.6.1

Fixed Bugs and Malfunctions

FIxed a bug if the erlang emulator was linked with a very old cryptolib version (1.0.1 or earlier).

The bug now fixed could have triggered a core dump if an unknown cipher name was used in crypto functions.

Own Id: OTP-16202

Crypto 4.6

Fixed Bugs and Malfunctions

The implementation of crypto_one_time/4 is adjusted to match the type specification. The spec and the black-box behaviour of the function are unchanged.

Some details: Both the spec and the implementation were correct seen separately. But with both of them combined simultaneously with crypto_one_time/5 which was called by the implementation of crypto_one_time/4, an (obvious) error was detected by a Dialyzer with more thorough checking than usual.

Own Id: OTP-15884 Aux Id: ERL-974

When using crypto with FIPS mode enabled, the digests were not correctly handled.

Own Id: OTP-15911

A memory leak in error handling code in ng_crypto_init_nif is fixed.

Own Id: OTP-15924

Fixed the broken static build of the crypto nifs

Own Id: OTP-15928 Aux Id: PR-2296

Improvements and New Features

The Message Authentication Codes (MAC) CMAC, HMAC and Poly1305 are unified into common functions in the New Crypto API. See the manual for CRYPTO.

Own Id: OTP-13872

Crypto 4.5.1

Fixed Bugs and Malfunctions

The cipher aes-ctr was disabled by mistake in crypto:supports for cryptolibs before 1.0.1. It worked however in the encrypt and decrypt functions.

Own Id: OTP-15829

Crypto 4.5

Fixed Bugs and Malfunctions

Fixed a bug in error return for crypto:poly1305/2. It returned the atom notsup instead of the exception notsup.

* POTENTIAL INCOMPATIBILITY *

Own Id: OTP-15677

The cipher chacha20 was introduced in OpenSSL 1.1.0. However, it could in a very odd situation, fail for versions less than OpenSSL 1.1.0d. It is therefore disabled for those versions.

* POTENTIAL INCOMPATIBILITY *

Own Id: OTP-15678

Improvements and New Features

A new rand module algorithm, exro928ss (Xoroshiro928**), has been implemented. It has got a really long period and good statistical quality for all output bits, while still being only about 50% slower than the default algorithm.

The same generator is also used as a long period counter in a new crypto plugin for the rand module, algorithm crypto_aes. This plugin uses AES-256 to scramble the counter which buries any detectable statistical artifacts. Scrambling is done in chunks which are cached to get good amortized speed (about half of the default algorithm).

Own Id: OTP-14461 Aux Id: PR-1857

Crypto's single C-file is split into multiple files. The different coding styles in the different parts are unified into a single style.

Own Id: OTP-14732 Aux Id: PR-2068, PR-2095

Build configuration of the crypto application has been moved from the erts application into the crypto application.

Own Id: OTP-15129

Adds two hash functions blake2b and blake2s (64 bit hash and 32 bit hash respectively). These are modern and standard hash functions used in blockchains and encrypted communication protocols. The hash functions are available in OpenSSL since version 1.1.1.

Own Id: OTP-15564 Aux Id: PR-2129

A new API is implemented in crypto. See the CRYPTO user's guide, chapter New and Old API for more information.

The old api with the crypto:block_* and crypto:stream_* interfaces are kept for compatibility, but implemented with the new api. Please note that since the error checking is more thorough, there might be arguments with for example faulty lengths that are no longer accepted.

* POTENTIAL INCOMPATIBILITY *

Own Id: OTP-15644 Aux Id: OTP-14732 , OTP-15451, PR-1857 , PR-2068, PR-2095

The new hash_info/1 and cipher_info/1 functions returns maps with information about the hash or cipher in the argument.

Own Id: OTP-15655 Aux Id: PR-2173, ERL-864, PR-2186

Obey additional OpenSSL configure flags when compiling the C-part of the CRYPTO application: no-bf, no-blake2, no-chacha, no-cmac, no-dh, no-dsa, no-md4, no-poly1305, no-rc2, no-rc4 and no-rmd160.

Own Id: OTP-15683

A new function crypto:supports/1 is introduced. The single argument takes an atom as argument: hashes, public_keys, ciphers, macs, curves or rsa_opts. The return value is a list of supported algorithms.

The difference with the existing crypto:supports/0 is, apart from the argument and the return value, that the old function reports what is supported by the old api, and the new function reports algorithms in the new api.

Own Id: OTP-15771

Crypto 4.4.2.3

Fixed Bugs and Malfunctions

Adding missing flag in BN-calls in SRP.

Own Id: OTP-17107

Crypto 4.4.2.2

Fixed Bugs and Malfunctions

Constant time comparisons added.

Own Id: OTP-16376

Crypto 4.4.2.1

Improvements and New Features

The ciphers aes_cfb8 and aes_cfb128 are now using the EVP interface. The supported key lengths are 128, 192 and 256 bits.

Own Id: OTP-16133 Aux Id: PR-2407

The ciphers aes_cfb8 and aes_cfb128 are now available in FIPS enabled mode.

Own Id: OTP-16134 Aux Id: PR-2407

Crypto 4.4.2

Fixed Bugs and Malfunctions

Fixed build link error on Windows. Unresolved symbol 'bcmp'.

Own Id: OTP-15750 Aux Id: ERL-905

Crypto 4.4.1

Fixed Bugs and Malfunctions

Fixes a bug that caused crypto:sign and crypto:verify to return the error message badarg instead of notsup in one case. That case was when signing or verifying with eddsa keys (that is, ed15519 or ed448), but only when FIPS was supported and enabled.

Own Id: OTP-15634

Improvements and New Features

Added a crypto benchmark test suite.

Own Id: OTP-15447

Crypto 4.4

Fixed Bugs and Malfunctions

Updated the RSA options part in the crypto application's C-code, documentation and tests.

Own Id: OTP-15302

Improvements and New Features

Added ed25519 and ed448 sign/verify.

Requires OpenSSL 1.1.1 or higher as cryptolib under the OTP application crypto.

Own Id: OTP-15419 Aux Id: OTP-15094

Fixed valgrind warnings.

Own Id: OTP-15467

Crypto 4.3.3

Fixed Bugs and Malfunctions

The RSA options rsa_mgf1_md, rsa_oaep_md, and rsa_oaep_label were always disabled. They will now be enabled when a suitable cryptolib is used.

They are still experimental and may change without prior notice.

Own Id: OTP-15212 Aux Id: ERL-675, PR1899, PR838

The ciphers aes_ige256 and blowfish_cbc had naming issues in crypto:next_iv/2.

Own Id: OTP-15283

the RSA_SSLV23_PADDING is disabled if LibreSSL is used as cryptlib. This is due to compilation problems.

This will be investigated further in the future.

Own Id: OTP-15303

Improvements and New Features

The supported named elliptic curves are now reported in crypto:supports/0 in a new entry tagged by 'curves'.

The function crypto:ec_curves/0 is kept for compatibility.

Own Id: OTP-14717 Aux Id: OTP-15244

The typing in the CRYPTO and PUBLIC_KEY applications are reworked and a few mistakes are corrected.

The documentation is now generated from the typing and some clarifications are made.

A new chapter on Algorithm Details such as key sizes and availability is added to the CRYPTO User's Guide.

Own Id: OTP-15134

Support for SHA3 both as a separate hash and in HMAC is now available if OpenSSL 1.1.1 or higher is used as cryptolib.

Available lengths are reported in the 'hashs' entry in crypto:supports/0 as sha3_*.

Own Id: OTP-15153

The mac algorithm poly1305 and the cipher algorithm chacha20 are now supported if OpenSSL 1.1.1 or higher is used as cryptolib.

Own Id: OTP-15164 Aux Id: OTP-15209

The key exchange Edward curves x25519 and x448 are now supported if OpenSSL 1.1.1 or higher is used as cryptolib.

Own Id: OTP-15240 Aux Id: OTP-15133

The supported RSA options for sign/verify and encrypt/decrypt are now reported in crypto:supports/0 in a new entry tagged by 'rsa_opts'.

The exakt set is still experimental and may change without prior notice.

Own Id: OTP-15260

The cipher aes_ccm is added.

Own Id: OTP-15286

Crypto 4.3.2

Fixed Bugs and Malfunctions

Update the crypto engine functions to handle multiple loads of an engine.

engine_load/3/4 is updated so it doesn't add the engine ID to OpenSSLs internal list of engines which makes it possible to run the engine_load more than once if it doesn't contain global data.

Added ensure_engine_loaded/2/3 which guarantees that the engine just is loaded once and the following calls just returns a reference to it. This is done by add the ID to the internal OpenSSL list and check if it is already registered when the function is called.

Added ensure_engine_unloaded/1/2 to unload engines loaded with ensure_engine_loaded.

Then some more utility functions are added.

engine_add/1, adds the engine to OpenSSL internal list

engine_remove/1, remove the engine from OpenSSL internal list

engine_get_id/1, fetch the engines id

engine_get_name/1, fetch the engine name

Own Id: OTP-15233

Crypto 4.3.1

Fixed Bugs and Malfunctions

Fixed a node crash in crypto:compute_key(ecdh, ...) when passing a wrongly typed Others argument.

Own Id: OTP-15194 Aux Id: ERL-673

Crypto 4.3

Fixed Bugs and Malfunctions

Removed two undocumented and erroneous functions (crypto:dh_generate_parameters/2 and crypto:dh_check/1).

Own Id: OTP-14956 Aux Id: ERL-579

Fixed bug causing VM crash if doing runtime upgrade of a crypto module built against OpenSSL older than 0.9.8h. Bug exists since OTP-20.2.

Own Id: OTP-15088

Improvements and New Features

A new rand plugin algorithm has been implemented in crypto, that is: crypto_cache. It uses strong random bytes as randomness source and caches them to get good speed. See crypto:rand_seed_alg/1.

Own Id: OTP-13370 Aux Id: PR-1573

Diffie-Hellman key functions are re-written with the EVP_PKEY api.

Own Id: OTP-14864

Crypto 4.2.2.4

Fixed Bugs and Malfunctions

Constant time comparisons added.

Own Id: OTP-16376

Crypto 4.2.2.3

Improvements and New Features

The ciphers aes_cfb8 and aes_cfb128 are now using the EVP interface. The supported key lengths are 128, 192 and 256 bits.

Own Id: OTP-16133 Aux Id: PR-2407

Crypto 4.2.2.1

Fixed Bugs and Malfunctions

Fixed a node crash in crypto:compute_key(ecdh, ...) when passing a wrongly typed Others argument.

Own Id: OTP-15194 Aux Id: ERL-673

Crypto 4.2.2

Fixed Bugs and Malfunctions

If OPENSSL_NO_EC was set, the compilation of the crypto nifs failed.

Own Id: OTP-15073

C-compile errors for LibreSSL 2.7.0 - 2.7.2 fixed

Own Id: OTP-15074 Aux Id: ERL-618

Crypto 4.2.1

Fixed Bugs and Malfunctions

Fix build error caused by removed RSA padding functions in LibreSSL >= 2.6.1

Own Id: OTP-14873

Crypto 4.2

Fixed Bugs and Malfunctions

The compatibility function void HMAC_CTX_free in crypto.c erroneously tried to return a value.

Own Id: OTP-14720

Improvements and New Features

Rewrite public and private key encode/decode with EVP api. New RSA padding options added. This is a modified half of PR-838.

Own Id: OTP-14446

The crypto API is extended to use private/public keys stored in an Engine for sign/verify or encrypt/decrypt operations.

The ssl application provides an API to use this new engine concept in TLS.

Own Id: OTP-14448

Add support to plug in alternative implementations for some or all of the cryptographic operations supported by the OpenSSL Engine API. When configured appropriately, OpenSSL calls the engine's implementation of these operations instead of its own.

Own Id: OTP-14567

Replaced a call of the OpenSSL deprecated function DH_generate_parameters in crypto.c.

Own Id: OTP-14639

Documentation added about how to use keys stored in an Engine.

Own Id: OTP-14735 Aux Id: OTP-14448

Add engine_ ctrl_cmd_string/3,4 the OpenSSL Engine support in crypto.

Own Id: OTP-14801

Crypto 4.1

Fixed Bugs and Malfunctions

On macOS, crypto would crash if observer had been started before crypto. On the beta for macOS 10.13 (High Sierra), crypto would crash. Both of those bugs have been fixed.

Own Id: OTP-14499 Aux Id: ERL-251 ERL-439

Improvements and New Features

Extend crypto:sign, crypto:verify, public_key:sign and public_key:verify with:

* support for RSASSA-PS padding for signatures and for saltlength setting
* X9.31 RSA padding.
* sha, sha224, sha256, sha384, and sha512 for dss signatures as mentioned in NIST SP 800-57 Part 1.
* ripemd160 to be used for rsa signatures.

This is a manual merge of half of the pull request 838 by potatosalad from Sept 2015.

Own Id: OTP-13704 Aux Id: PR838

A new tuple in crypto:supports/0 reports supported MAC algorithms.

Own Id: OTP-14504

Crypto 4.0

Fixed Bugs and Malfunctions

LibreSSL can now be used by the modernized crypto app.

Own Id: OTP-14247

Add compile option -compile(no_native) in modules with on_load directive which is not yet supported by HiPE.

Own Id: OTP-14316 Aux Id: PR-1390

Fix a bug in aes cfb128 function introduced by the bug fix in GitHub pull request #1393.

Own Id: OTP-14435 Aux Id: PR-1462, PR-1393, OTP-14313

Improvements and New Features

Add basic support for CMAC

Own Id: OTP-13779 Aux Id: ERL-82 PR-1138

Removed functions deprecated in crypto-3.0 first released in OTP-R16B01

* POTENTIAL INCOMPATIBILITY *

Own Id: OTP-13873

The crypto application now supports OpenSSL 1.1.

Own Id: OTP-13900

Allow Erlang/OTP to use OpenSSL in FIPS-140 mode, in order to satisfy specific security requirements (mostly by different parts of the US federal government).

See the new crypto users guide "FIPS mode" chapter about building and using the FIPS support which is disabled by default.

(Thanks to dszoboszlay and legoscia)

Own Id: OTP-13921 Aux Id: PR-1180

Crypto chacha20-poly1305 as in RFC 7539 enabled for OpenSSL >= 1.1.

Thanks to mururu.

Own Id: OTP-14092 Aux Id: PR-1291

RSA key generation added to crypto:generate_key/2. Thanks to wiml.

An interface is also added to public_key:generate_key/1.

Own Id: OTP-14140 Aux Id: ERL-165, PR-1299

Raised minimum requirement for OpenSSL version to OpenSSL-0.9.8.c although we recommend a much higher version, that is a version that is still maintained officially by the OpenSSL project. Note that using such an old version may restrict the crypto algorithms supported.

* POTENTIAL INCOMPATIBILITY *

Own Id: OTP-14171

Deprecate crypto:rand_uniform/2 as it is not cryptographically strong

Own Id: OTP-14274

The Crypto application now supports generation of cryptographically strong random numbers (floats < 1.0 and integer arbitrary ranges) as a plugin to the 'rand' module.

Own Id: OTP-14317 Aux Id: PR-1372

This replaces the hard coded test values for AES, CMAC and GCM ciphers with the full validation set from NIST's CAVP program.

Own Id: OTP-14436 Aux Id: PR-1396

Crypto 3.7.4

Fixed Bugs and Malfunctions

Fix a bug with AES CFB 128 for 192 and 256 bit keys. Thanks to kellymclaughlin !

Own Id: OTP-14313 Aux Id: PR-1393

Crypto 3.7.3

Improvements and New Features

The implementation of the key exchange algorithms diffie-hellman-group-exchange-sha* are optimized, up to a factor of 11 for the slowest ( = biggest and safest) group size.

Own Id: OTP-14169 Aux Id: seq-13261

Crypto 3.7.2

Fixed Bugs and Malfunctions

The crypto application has been fixed to not use RC2 against OpenSSL built with RC2 disabled.

Own Id: OTP-13895 Aux Id: PR-1163

The crypto application has been fixed to not use RC4 against OpenSSL built with RC4 disabled.

Own Id: OTP-13896 Aux Id: PR-1169

Improvements and New Features

To ease troubleshooting, erlang:load_nif/2 now includes the return value from a failed call to load/reload/upgrade in the text part of the error tuple. The crypto NIF makes use of this feature by returning the source line where/if the initialization fails.

Own Id: OTP-13951

Crypto 3.7.1

Fixed Bugs and Malfunctions

Crypto has been fixed to work against OpenSSL versions with disabled DES ciphers. Correct spelling of cipher algorithm 'des3_cfb' has been introduced; the previous misspeling still works.

Own Id: OTP-13783 Aux Id: ERL-203

The size of an internal array in crypto has been fixed to not segfault when having all possible ciphers. Bug fix by Duncan Overbruck.

Own Id: OTP-13789 Aux Id: PR-1140

Crypto 3.7

Improvements and New Features

Refactor crypto to use the EVP interface of OpenSSL, which is the recommended interface that also enables access to hardware acceleration for some operations.

Own Id: OTP-12217

Add support for 192-bit keys for the aes_cbc cipher.

Own Id: OTP-13206 Aux Id: pr 832

Add support for 192-bit keys for aes_ecb.

Own Id: OTP-13207 Aux Id: pr829

Deprecate the function crypto:rand_bytes and make sure that crypto:strong_rand_bytes is used in all places that are cryptographically significant.

Own Id: OTP-13214

Enable AES-GCM encryption/decryption to change the tag length between 1 to 16 bytes.

Own Id: OTP-13483 Aux Id: PR-998

Crypto 3.6.3

Fixed Bugs and Malfunctions

Fix bug for aes_ecb block crypto when data is larger than 16 bytes.

Own Id: OTP-13249

Improve portability of ECC tests in Crypto and SSL for "exotic" OpenSSL versions.

Own Id: OTP-13311

Crypto 3.6.2

Fixed Bugs and Malfunctions

Small documentation fixes

Own Id: OTP-13017

Crypto 3.6.1

Fixed Bugs and Malfunctions

Make crypto:ec_curves/0 return empty list if elliptic curve is not supported at all.

Own Id: OTP-12944

Crypto 3.6

Fixed Bugs and Malfunctions

Enhance crypto:generate_key to calculate ECC public keys from private key.

Own Id: OTP-12394

Fix bug in crypto:generate_key for ecdh that could cause VM crash for faulty input.

Own Id: OTP-12733

Improvements and New Features

Use the EVP API for AES-CBC crypto to enables the use of hardware acceleration for AES-CBC crypto on newer Intel CPUs (AES-NI), among other platforms.

Own Id: OTP-12380

Add AES ECB block encryption.

Own Id: OTP-12403

Crypto 3.5

Improvements and New Features

Extend block_encrypt/decrypt for aes_cfb8 and aes_cfb128 to accept keys of length 128, 192 and 256 bits. Before only 128 bit keys were accepted.

Own Id: OTP-12467

Crypto 3.4.2

Improvements and New Features

Add configure option --with-ssl-incl=PATH to support OpenSSL installations with headers and libraries at different places.

Own Id: OTP-12215 Aux Id: seq12700

Add configure option --with-ssl-rpath to control which runtime library path to use for dynamic linkage toward OpenSSL.

Own Id: OTP-12316 Aux Id: seq12753

Crypto 3.4.1

Fixed Bugs and Malfunctions

Make crypto verify major version number of OpenSSL header files and runtime library. Loading of crypto will fail if there is a version mismatch.

Own Id: OTP-12146 Aux Id: seq12700

Crypto 3.4

Fixed Bugs and Malfunctions

Fix memory leak in crypto:hmac_init/upgrade/final functions for all data and in crypto:hmac/3/4 for data larger than 20000 bytes. Bug exists since OTP 17.0.

Own Id: OTP-11953

Fix memory leak in crypto for elliptic curve.

Own Id: OTP-11999

Improvements and New Features

Add aes_cfb8 cypher to crypto:block_encrypt and block_decrypt.

Own Id: OTP-11911

Crypto 3.3

Fixed Bugs and Malfunctions

Fix memory leaks and invalid deallocations in mod_pow, mod_exp and generate_key(srp,...) when bad arguments are passed. (Thanks to Florian Zumbiehi)

Own Id: OTP-11550

Correction of the word 'ChipherText' throughout the documentation (Thanks to Andrew Tunnell-Jones)

Own Id: OTP-11609

Fix fatal bug when using a hmac context variable in more than one call to hmac_update or hmac_final. The reuse of hmac contexts has never worked as the underlying OpenSSL implementation does not support it. It is now documented as having undefined behaviour, but it does not crash or corrupt the VM anymore.

Own Id: OTP-11724

Crypto handles out-of-memory with a controlled abort instead of crash/corruption. (Thanks to Florian Zumbiehi)

Own Id: OTP-11725

Application upgrade (appup) files are corrected for the following applications:

asn1, common_test, compiler, crypto, debugger, dialyzer, edoc, eldap, erl_docgen, et, eunit, gs, hipe, inets, observer, odbc, os_mon, otp_mibs, parsetools, percept, public_key, reltool, runtime_tools, ssh, syntax_tools, test_server, tools, typer, webtool, wx, xmerl

A new test utility for testing appup files is added to test_server. This is now used by most applications in OTP.

(Thanks to Tobias Schlager)

Own Id: OTP-11744

Improvements and New Features

By giving --enable-static-{nifs,drivers} to configure it is now possible to statically linking of nifs and drivers to the main Erlang VM binary. At the moment only the asn1 and crypto nifs of the Erlang/OTP nifs and drivers have been prepared to be statically linked. For more details see the Installation Guide in the System documentation.

Own Id: OTP-11258

Add IGE mode for AES cipher in crypto (Thanks to Yura Beznos).

Own Id: OTP-11522

Moved elliptic curve definition from the crypto NIF/OpenSSL into Erlang code, adds the RFC-5639 brainpool curves and makes TLS use them (RFC-7027).

Thanks to Andreas Schultz

Own Id: OTP-11578

Remove all obsolete application processes from crypto and make it into a pure library application.

Own Id: OTP-11619

Crypto 3.2

Fixed Bugs and Malfunctions

Fix uninitialized pointers in crypto (Thanks to Anthony Ramine)

Own Id: OTP-11510

Crypto 3.1

Improvements and New Features

Refactor ecdsa cipher to simplify code and improve performance.

Own Id: OTP-11320

Crypto 3.0

Improvements and New Features

Integrate elliptic curve contribution from Andreas Schultz

In order to be able to support elliptic curve cipher suites in SSL/TLS, additions to handle elliptic curve infrastructure has been added to public_key and crypto.

This also has resulted in a rewrite of the crypto API to gain consistency and remove unnecessary overhead. All OTP applications using crypto has been updated to use the new API.

Impact: Elliptic curve cryptography (ECC) offers equivalent security with smaller key sizes than other public key algorithms. Smaller key sizes result in savings for power, memory, bandwidth, and computational cost that make ECC especially attractive for constrained environments.

Own Id: OTP-11009

Fixed a spelling mistake in crypto docs. Thanks to Klaus Trainer

Own Id: OTP-11058

Known Bugs and Problems

Make the crypto functions interruptible by chunking input when it is very large and bumping reductions in the nifs.

Not yet implemented for block_encrypt|decrypt/4

Impact: Individual calls to crypto functions may take longer time but over all system performance should improve as crypto calls will not become throughput bottlenecks.

Own Id: OTP-11142

Crypto 2.3

Improvements and New Features

Enable runtime upgrade of crypto including the OpenSSL library used by crypto.

Own Id: OTP-10596

Improve documentation and tests for hmac functions in crypto. Thanks to Daniel White

Own Id: OTP-10640

Added ripemd160 support to crypto. Thanks to Michael Loftis

Own Id: OTP-10667

Crypto 2.2

Fixed Bugs and Malfunctions

Remove unnecessary dependency to libssl from crypto NIF library. This dependency was introduced by accident in R14B04.

Own Id: OTP-10064

Improvements and New Features

Add crypto and public_key support for the hash functions SHA224, SHA256, SHA384 and SHA512 and also hmac and rsa_sign/verify support using these hash functions. Thanks to Andreas Schultz for making a prototype.

Own Id: OTP-9908

Optimize RSA private key handling in crypto and public_key.

Own Id: OTP-10065

Make crypto:aes_cfb_128_encrypt and crypto:aes_cfb_128_decrypt handle data and cipher with arbitrary length. (Thanks to Stefan Zegenhagen)

Own Id: OTP-10136

Crypto 2.1

Improvements and New Features

public_key, ssl and crypto now supports PKCS-8

Own Id: OTP-9312

Erlang/OTP can now be built using parallel make if you limit the number of jobs, for instance using 'make -j6' or 'make -j10'. 'make -j' does not work at the moment because of some missing dependencies.

Own Id: OTP-9451

Add DES and Triple DES cipher feedback (CFB) mode functions to crypto. (Thanks to Paul Guyot)

Own Id: OTP-9640

Add sha256, sha384 and sha512 support for crypto:rsa_verify.

Own Id: OTP-9778

Crypto 2.0.4

Fixed Bugs and Malfunctions

crypto:rand_uniform works correctly for negative integers. Fails with badarg exception for invalid ranges (when Hi =< Lo) instead of returning incorrect output.

Own Id: OTP-9526

Fix win32 OpenSSL static linking (Thanks to Dave Cottlehuber)

Own Id: OTP-9532

Crypto 2.0.3

Fixed Bugs and Malfunctions

Various small documentation fixes (Thanks to Bernard Duggan)

Own Id: OTP-9172

Improvements and New Features

New crypto support for streaming of AES CTR and HMAC. (Thanks to Travis Jensen)

Own Id: OTP-9275

Due to standard library DLL mismatches between versions of OpenSSL and Erlang/OTP, OpenSSL is now linked statically to the crypto driver on Windows. This fixes problems starting crypto when running Erlang as a service on all Windows versions.

Own Id: OTP-9280

Crypto 2.0.2.2

Improvements and New Features

Strengthened random number generation. (Thanks to Geoff Cant)

Own Id: OTP-9225

Crypto 2.0.2.1

Improvements and New Features

Misc. Updates.

Own Id: OTP-9132

Crypto 2.0.2

Improvements and New Features

AES CTR encryption support in crypto.

Own Id: OTP-8752 Aux Id: seq11642

Crypto 2.0.1

Fixed Bugs and Malfunctions

Crypto dialyzer type error in md5_mac and sha_mac.

Own Id: OTP-8718

RC4 stream cipher didn't work. This since the new NIF implementation of crypto:rc4_encrypt_with_state/2 introduced in crypto-2.0 didn't return an updated state. (Thanks to Paul Guyot)

Own Id: OTP-8781

A number of memory leaks in the crypto NIF library have been fixed.

Own Id: OTP-8810

Improvements and New Features

Added erlang:system_info(build_type) which makes it easier to chose drivers, NIF libraries, etc based on build type of the runtime system.

The NIF library for crypto can now be built for valgrind and/or debug as separate NIF libraries that will be automatically loaded if the runtime system has been built with a matching build type.

Own Id: OTP-8760

Crypto 2.0

Improvements and New Features

crypto application changed to use NIFs instead of driver.

Own Id: OTP-8333

des_ecb_encrypt/2 and des_ecb_decrypt/2 has been added to the crypto module. The crypto:md4/1 function has been documented.

Own Id: OTP-8551

The undocumented, unsupported, and deprecated function lists:flat_length/1 has been removed.

Own Id: OTP-8584

New variants of crypto:dss_sign and crypto:dss_verify with an extra argument to control how the digest is calculated.

Own Id: OTP-8700

Crypto 1.6.4

Improvements and New Features

Cross compilation improvements and other build system improvements.

Most notable:

Lots of cross compilation improvements. The old cross compilation support was more or less non-existing as well as broken. Please, note that the cross compilation support should still be considered as experimental. Also note that old cross compilation configurations cannot be used without modifications. For more information on cross compiling Erlang/OTP see the $ERL_TOP/INSTALL-CROSS.md file.

Support for staged install using DESTDIR. The old broken INSTALL_PREFIX has also been fixed. For more information see the $ERL_TOP/INSTALL.md file.

Documentation of the release target of the top Makefile. For more information see the $ERL_TOP/INSTALL.md file.

make install now by default creates relative symbolic links instead of absolute ones. For more information see the $ERL_TOP/INSTALL.md file.

$ERL_TOP/configure --help=recursive now works and prints help for all applications with configure scripts.

Doing make install, or make release directly after make all no longer triggers miscellaneous rebuilds.

Existing bootstrap system is now used when doing make install, or make release without a preceding make all.

The crypto and ssl applications use the same runtime library path when dynamically linking against libssl.so and libcrypto.so. The runtime library search path has also been extended.

The configure scripts of erl_interface and odbc now search for thread libraries and thread library quirks the same way as ERTS do.

The configure script of the odbc application now also looks for odbc libraries in lib64 and lib/64 directories when building on a 64-bit system.

The config.h.in file in the erl_interface application is now automatically generated in instead of statically updated which reduces the risk of configure tests without any effect.

(Thanks to Henrik Riomar for suggestions and testing)

(Thanks to Winston Smith for the AVR32-Linux cross configuration and testing)

* POTENTIAL INCOMPATIBILITY *

Own Id: OTP-8323

The crypto module now supports Blowfish in ECB, CBC and OFB modes. (Thanks to Paul Oliver.)

Own Id: OTP-8331

The documentation is now possible to build in an open source environment after a number of bugs are fixed and some features are added in the documentation build process.

- The arity calculation is updated.

- The module prefix used in the function names for bif's are removed in the generated links so the links will look like "http://www.erlang.org/doc/man/erlang.html#append_element-2" instead of "http://www.erlang.org/doc/man/erlang.html#erlang:append_element-2".

- Enhanced the menu positioning in the html documentation when a new page is loaded.

- A number of corrections in the generation of man pages (thanks to Sergei Golovan)

- The legal notice is taken from the xml book file so OTP's build process can be used for non OTP applications.

Own Id: OTP-8343

Crypto 1.6.3

Fixed Bugs and Malfunctions

Suppressed false valgrind errors caused by libcrypto using uninitialized data as entropy.

Own Id: OTP-8200

Improvements and New Features

The documentation is now built with open source tools (xsltproc and fop) that exists on most platforms. One visible change is that the frames are removed.

Own Id: OTP-8201

When the crypto application failed to load the OpenSSL/LibEAY shared object, error indication was sparse. Now a more specific error message is sent to the error logger.

Own Id: OTP-8281

Crypto 1.6.2

Fixed Bugs and Malfunctions

Fixed emulator crash caused by crypto using an old openssl version that did not cope with large file descriptors.

Own Id: OTP-8261 Aux Id: seq11434

Crypto 1.6.1

Fixed Bugs and Malfunctions

Makefile.in has been updated to use the LDFLAGS environment variable (if set). (Thanks to Davide Pesavento.)

Own Id: OTP-8157

Improvements and New Features

Support for Blowfish cfb64 added to crypto.

Own Id: OTP-8096

New function crypto:aes_cbc_ivec

Own Id: OTP-8141

Crypto 1.6

Fixed Bugs and Malfunctions

The dh_compute_key sometimes returned a SharedSecret of incorrect size.

Own Id: OTP-7674

Improvements and New Features

Optimization for drivers by creating small binaries direct on process heap.

Own Id: OTP-7762

Crypto 1.5.3

Improvements and New Features

Added new functions: dss_verify/3, rsa_verify/3, rsa_verify/4, dss_sign/2, rsa_sign/2, rsa_sign/3, rsa_public_encrypt, rsa_private_decrypt/3, rsa_private_encrypt/3, rsa_public_decrypt/3, dh_generate_key/1, dh_generate_key/2, dh_compute_key/3.

Own Id: OTP-7545

Crypto 1.5.2.1

Improvements and New Features

Minor performance optimization.

Own Id: OTP-7521

Crypto 1.5.2

Fixed Bugs and Malfunctions

./configure has been improved to find 64-bit OpenSSL libraries.

Own Id: OTP-7270

Improvements and New Features

crypto and zlib drivers improved to allow concurrent smp access.

Own Id: OTP-7262

Crypto 1.5.1.1

Improvements and New Features

The linked in driver for the crypto application is now linked statically against the OpenSSL libraries, to avoid installation and runtime problems in connection to the OpenSSL library locations.

Own Id: OTP-6680

Minor Makefile changes.

Own Id: OTP-6689

Crypto 1.5

Improvements and New Features

It is now explicitly checked at start-up that the crypto driver is properly loaded (Thanks to Claes Wikstrom).

Own Id: OTP-6109

Crypto 1.4

Improvements and New Features

The previously undocumented and UNSUPPORTED ssh application has been updated and documented. This release of the ssh application is still considered to be a beta release and (if necessary) there could still be changes in its API before it reaches 1.0.

Also, more cryptographic algorithms have been added to the crypto application.

* POTENTIAL INCOMPATIBILITY *

Own Id: OTP-5631

Crypto 1.3

Improvements and New Features

Added support for RFC 3826 - The Advanced Encryption Standard (AES) Cipher Algorithm in the SNMP User-based Security Model.
Martin Björklund

Crypto 1.2.3

Fixed Bugs and Malfunctions

Linked in drivers in the crypto, and asn1 applications are now compiled with the -D_THREAD_SAFE and -D_REENTRANT switches on unix when the emulator has thread support enabled.

Linked in drivers on MacOSX are not compiled with the undocumented -lbundle1.o switch anymore. Thanks to Sean Hinde who sent us a patch.

Linked in driver in crypto, and port programs in ssl, now compiles on OSF1.

Minor makefile improvements in runtime_tools.

Own Id: OTP-5346

Crypto 1.2.2

Improvements and New Features

Corrected error handling. If the port to the driver that crypto uses is unexpectedly closed (which should not happen during normal operation of crypto), crypto will terminate immediately (rather than crashing the next time crypto is used). Also corrected build problems on Mac OS X.

Own Id: OTP-5279

Crypto 1.2.1

Fixed Bugs and Malfunctions

It was not possible in R9 to relink the crypto driver. The object file was missing as well as an example makefile. The crypto driver object file is now released with the application (installed in priv/obj). An example makefile has also been added to the priv/obj directory. The makefile serves as an example of how to relink the driver on Unix (crypto_drv.so) or Windows (crypto_drv.dll).

Own Id: OTP-4828 Aux Id: seq8193

Crypto 1.2

Improvements and New Features

Previous versions of Crypto where delivered with statically linked binaries based on SSLeay. That is not longer the case. The current version of Crypto requires dynamically linked OpenSSL libraries that the user has to install. The library needed is libcrypto.so (Unix) or libeay32.[lib|dll] (Win32). For further details see the crypto(6) application manual page.

This version of Crypto uses the new DES interface of OpenSSL 0.9.7, which is not backward compatible with earlier versions of OpenSSL.

The functions des_ede3_cbc_encrypt/5 and des_ede3_cbc_decrypt/5 have been renamed to des3_cbc_encrypt/5 and des3_cbc_decrypt/5, respectively. The old functions have been retained (they are deprecated and not listed in the crypto(3) manual page).

Reported Fixed Bugs and Malfunctions

The start of crypto failed on Windows, due to erroneous addition of a DES3 algorithm.

Own Id: OTP-4684
Aux Id: seq7864

Crypto 1.1.3

Reported Fixed Bugs and Malfunctions

To obtain backward compatibility with the old SSLeay package, and with earlier versions of OpenSSL, the macro OPENSSL_DES_LIBDES_COMPATIBILITY has been added to crypto_drv.c. This is of importance only for the open source version of Crypto.

Crypto 1.1.2

Reported Fixed Bugs and Malfunctions

In the manual page crypto the function names md5_finish and sha_finish have been changed to md5_final and sha_final to correctly document the implementation.

Own Id: OTP-3409

Crypto 1.1.1

Code replacement in runtime is supported. Upgrade can be done from from version 1.1 and downgrade to version 1.1.

Improvements and New Features

The driver part of the Crypto application has been updated to use the erl_driver header file. Version 1.1.1 requires emulator version 4.9.1 or later.

Crypto 1.1

Reported Fixed Bugs and Malfunctions

On Windows the crypto_drv was incorrectly linked to static run-time libraries instead of dynamic ones.

Own Id: OTP-3240

Crypto 1.0

New application.

FIPS mode

This chapter describes FIPS mode support in the crypto application.

Background

OpenSSL can be built to provide FIPS 140-2 validated cryptographic services. It is not the OpenSSL application that is validated, but a special software component called the OpenSSL FIPS Object Module. However applications do not use this Object Module directly, but through the regular API of the OpenSSL library.

The crypto application supports using OpenSSL in FIPS mode. In this scenario only the validated algorithms provided by the Object Module are accessible, other algorithms usually available in OpenSSL (like md5) or implemented in the Erlang code (like SRP) are disabled.

Enabling FIPS mode

Build or install the FIPS Object Module and a FIPS enabled OpenSSL library.

You should read and precisely follow the instructions of the Security Policy and User Guide.

Warning

It is very easy to build a working OpenSSL FIPS Object Module and library from the source. However it does not qualify as FIPS 140-2 validated if the numerous restrictions in the Security Policy are not properly followed.

Configure and build Erlang/OTP with FIPS support:

$ cd $ERL_TOP
$ ./otp_build configure --enable-fips
...
checking for FIPS_mode_set... yes
...
$ make

If FIPS_mode_set returns no the OpenSSL library is not FIPS enabled and crypto won't support FIPS mode either.

Set the fips_mode configuration setting of the crypto application to true before loading the crypto module.

The best place is in the sys.config system configuration file of the release.

Start and use the crypto application as usual. However take care to avoid the non-FIPS validated algorithms, they will all throw exception not_supported.

Entering and leaving FIPS mode on a node already running crypto is not supported. The reason is that OpenSSL is designed to prevent an application requesting FIPS mode to end up accidentally running in non-FIPS mode. If entering FIPS mode fails (e.g. the Object Module is not found or is compromised) any subsequent use of the OpenSSL API would terminate the emulator.

An on-the-fly FIPS mode change would thus have to be performed in a critical section protected from any concurrently running crypto operations. Furthermore in case of failure all crypto calls would have to be disabled from the Erlang or nif code. This would be too much effort put into this not too important feature.

Incompatibilities with regular builds

The Erlang API of the crypto application is identical regardless of building with or without FIPS support. However the nif code internally uses a different OpenSSL API.

This means that the context (an opaque type) returned from streaming crypto functions (hash_(init|update|final), hmac_(init|update|final) and stream_(init|encrypt|decrypt)) is different and incompatible with regular builds when compiling crypto with FIPS support.

Common caveats

In FIPS mode non-validated algorithms are disabled. This may cause some unexpected problems in application relying on crypto.

Warning

Do not try to work around these problems by using alternative implementations of the missing algorithms! An application can only claim to be using a FIPS 140-2 validated cryptographic module if it uses it exclusively for every cryptographic operation.

Restrictions on key sizes

Although public key algorithms are supported in FIPS mode they can only be used with secure key sizes. The Security Policy requires the following minimum values:

RSA - 1024 bit

DSS - 1024 bit

EC algorithms - 160 bit

Restrictions on elliptic curves

The Erlang API allows using arbitrary curve parameters, but in FIPS mode only those allowed by the Security Policy shall be used.

Avoid md5 for hashing

Md5 is a popular choice as a hash function, but it is not secure enough to be validated. Try to use sha instead wherever possible.

For exceptional, non-cryptographic use cases one may consider switching to erlang:md5/1 as well.

Certificates and encrypted keys

As md5 is not available in FIPS mode it is only possible to use certificates that were signed using sha hashing. When validating an entire certificate chain all certificates (including the root CA's) must comply with this rule.

For similar dependency on the md5 and des algorithms most encrypted private keys in PEM format do not work either. However, the PBES2 encryption scheme allows the use of stronger FIPS verified algorithms which is a viable alternative.

SNMP v3 limitations

It is only possible to use usmHMACSHAAuthProtocol and usmAesCfb128Protocol for authentication and privacy respectively in FIPS mode. The snmp application however won't restrict selecting disabled protocols in any way, and using them would result in run time crashes.

TLS 1.2 is required

All SSL and TLS versions prior to TLS 1.2 use a combination of md5 and sha1 hashes in the handshake for various purposes:

Authenticating the integrity of the handshake messages.

In the exchange of DH parameters in cipher suites providing non-anonymous PFS (perfect forward secrecy).

In the PRF (pseud-random function) to generate keying materials in cipher suites not using PFS.

OpenSSL handles these corner cases in FIPS mode, however the Erlang crypto and ssl applications are not prepared for them and therefore you are limited to TLS 1.2 in FIPS mode.

On the other hand it worth mentioning that at least all cipher suites that would rely on non-validated algorithms are automatically disabled in FIPS mode.

Note

Certificates using weak (md5) digests may also cause problems in TLS. Although TLS 1.2 has an extension for specifying which type of signatures are accepted, and in FIPS mode the ssl application will use it properly, most TLS implementations ignore this extension and simply send whatever certificates they were configured with.

Engine Load

This chapter describes the support for loading encryption engines in the crypto application.

Background

OpenSSL exposes an Engine API, which makes it possible to plug in alternative implementations for some or all of the cryptographic operations implemented by OpenSSL. When configured appropriately, OpenSSL calls the engine's implementation of these operations instead of its own.

Typically, OpenSSL engines provide a hardware implementation of specific cryptographic operations. The hardware implementation usually offers improved performance over its software-based counterpart, which is known as cryptographic acceleration.

Note

The file name requirement on the engine dynamic library can differ between SSL versions.

Use Cases

Dynamically load an engine from default directory

If the engine is located in the OpenSSL/LibreSSL installation engines directory.

1> {ok, Engine} = crypto:engine_load(<<"otp_test_engine">>, [], []).
 {ok, #Ref}

Load an engine with the dynamic engine

Load an engine with the help of the dynamic engine by giving the path to the library.

 2> {ok, Engine} = crypto:engine_load(<<"dynamic">>,
                                      [{<<"SO_PATH">>,
                                        <<"/some/path/otp_test_engine.so">>},
                                       {<<"ID">>, <<"MD5">>},
                                       <<"LOAD">>],
                                      []).
 {ok, #Ref}

Load an engine and replace some methods

Load an engine with the help of the dynamic engine and just replace some engine methods.

 3> {ok, Engine} = crypto:engine_load(<<"dynamic">>,
                                      [{<<"SO_PATH">>,
                                        <<"/some/path/otp_test_engine.so">>},
                                       {<<"ID">>, <<"MD5">>},
                                       <<"LOAD">>],
                                      []).
{ok, #Ref}
4> ok = crypto:engine_register(Engine, [engine_method_digests]).
ok

Load with the ensure loaded function

This function makes sure the engine is loaded just once and the ID is added to the internal engine list of OpenSSL. The following calls to the function will check if the ID is loaded and then just get a new reference to the engine.

 5> {ok, Engine} = crypto:ensure_engine_loaded(<<"MD5">>,
                                               <<"/some/path/otp_test_engine.so">>).
 {ok, #Ref}

To remove the tag from the OpenSSL engine list use crypto:engine_remove/1.

 6> crypto:engine_remove(Engine).
 ok

To unload it use crypto:engine_unload/1 which removes the references to the engine.

 6> crypto:engine_unload(Engine).
 ok

List all engines currently loaded

 8> crypto:engine_list().
[<<"dynamic">>, <<"MD5">>]

Engine Stored Keys

This chapter describes the support in the crypto application for using public and private keys stored in encryption engines.

Background

OpenSSL exposes an Engine API, which makes it possible to plug in alternative implementations for some of the cryptographic operations implemented by OpenSSL. See the chapter Engine Load for details and how to load an Engine.

An engine could among other tasks provide a storage for private or public keys. Such a storage could be made safer than the normal file system. Those techniques are not described in this User's Guide. Here we concentrate on how to use private or public keys stored in such an engine.

The storage engine must call ENGINE_set_load_privkey_function and ENGINE_set_load_pubkey_function. See the OpenSSL cryptolib's manpages.

OTP/Crypto requires that the user provides two or three items of information about the key. The application used by the user is usually on a higher level, for example in SSL. If using the crypto application directly, it is required that:

an Engine is loaded, see the chapter on Engine Load or the Reference Manual

a reference to a key in the Engine is available. This should be an Erlang string or binary and depends on the Engine loaded

an Erlang map is constructed with the Engine reference, the key reference and possibly a key passphrase if needed by the Engine. See the Reference Manual for details of the map.

Use Cases

Sign with an engine stored private key

This example shows how to construct a key reference that is used in a sign operation. The actual key is stored in the engine that is loaded at prompt 1.

1> {ok, EngineRef} = crypto:engine_load(....).
...
{ok,#Ref<0.2399045421.3028942852.173962>}
2> PrivKey = #{engine => EngineRef,
               key_id => "id of the private key in Engine"}.
...
3> Signature = crypto:sign(rsa, sha, <<"The message">>, PrivKey).
<<65,6,125,254,54,233,84,77,83,63,168,28,169,214,121,76,
  207,177,124,183,156,185,160,243,36,79,125,230,231,...>>

Verify with an engine stored public key

Here the signature and message in the last example is verifyed using the public key. The public key is stored in an engine, only to exemplify that it is possible. The public key could of course be handled openly as usual.

4> PublicKey = #{engine => EngineRef,
                 key_id => "id of the public key in Engine"}.
...
5> crypto:verify(rsa, sha, <<"The message">>, Signature, PublicKey).
true
6>

Using a password protected private key

The same example as the first sign example, except that a password protects the key down in the Engine.

6> PrivKeyPwd = #{engine => EngineRef,
                  key_id => "id of the pwd protected private key in Engine",
		  password => "password"}.
...
7> crypto:sign(rsa, sha, <<"The message">>, PrivKeyPwd).
<<140,80,168,101,234,211,146,183,231,190,160,82,85,163,
  175,106,77,241,141,120,72,149,181,181,194,154,175,76,
  223,...>>
8>

Algorithm Details

This chapter describes details of algorithms in the crypto application.

The tables only documents the supported cryptos and key lengths. The user should not draw any conclusion on security from the supplied tables.

Ciphers

A cipher in the new api is categorized as either cipher_no_iv(), cipher_iv() or cipher_aead(). The letters IV are short for Initialization Vector and AEAD is an abbreviation of Authenticated Encryption with Associated Data.

Due to irregular naming conventions, some cipher names in the old api are substituted by new names in the new api. For a list of retired names, see Retired cipher names.

To dynamically check availability, check that the name in the Cipher and Mode column is present in the list returned by crypto:supports(ciphers).

Ciphers without an IV - cipher_no_iv()

To be used with:

crypto_one_time/4

crypto_init/3

The ciphers are:

Cipher and Mode | Key length [bytes] | Block size [bytes]
aes_128_ecb | 16 | 16
aes_192_ecb | 24 | 16
aes_256_ecb | 32 | 16
blowfish_ecb | 16 | 8
des_ecb | 8 | 8
rc4 | 16 | 1
sm4_ecb | 16 | 16

Table: Ciphers without IV

Ciphers with an IV - cipher_iv()

To be used with:

crypto_one_time/5

crypto_init/4

The ciphers are:

Cipher and Mode | Key length [bytes] | IV length [bytes] | Block size [bytes] | Limited to OpenSSL versions
aes_128_cbc | 16 | 16 | 16 |
aes_192_cbc | 24 | 16 | 16 |
aes_256_cbc | 32 | 16 | 16 |
aes_128_cfb8 | 16 | 16 | 1 |
aes_192_cfb8 | 24 | 16 | 1 |
aes_256_cfb8 | 32 | 16 | 1 |
aes_128_cfb128 | 16 | 16 | 1 |
aes_192_cfb128 | 24 | 16 | 1 |
aes_256_cfb128 | 32 | 16 | 1 |
aes_128_ctr | 16 | 16 | 1 |
aes_192_ctr | 24 | 16 | 1 |
aes_256_ctr | 32 | 16 | 1 |
aes_128_ofb | 16 | 16 | 1 |
aes_192_ofb | 24 | 16 | 1 |
aes_256_ofb | 32 | 16 | 1 |
blowfish_cbc | 16 | 8 | 8 |
blowfish_cfb64 | 16 | 8 | 1 |
blowfish_ofb64 | 16 | 8 | 1 |
chacha20 | 32 | 16 | 1 | ≥1.1.0d
des_cbc | 8 | 8 | 8 |
des_ede3_cbc | 24 | 8 | 8 |
des_cfb | 8 | 8 | 1 |
des_ede3_cfb | 24 | 8 | 1 |
rc2_cbc | 16 | 8 | 8 |
sm4_cbc | 16 | 16 | 16 | ≥1.1.1
sm4_cfb | 16 | 16 | 16 | ≥1.1.1
sm4_ofb | 16 | 16 | 16 | ≥1.1.1
sm4_ctr | 16 | 16 | 16 | ≥1.1.1

Table: Ciphers with IV

Ciphers with AEAD - cipher_aead()

To be used with:

crypto_one_time_aead/6

crypto_one_time_aead/7

The ciphers are:

Cipher and Mode | Key length [bytes] | IV length [bytes] | AAD length [bytes] | Tag length [bytes] | Block size [bytes] | Limited to OpenSSL versions
aes_128_ccm | 16 | 7-13 | any | even 4-16 default: 12 | any | ≥1.0.1
aes_192_ccm | 24 | 7-13 | any | even 4-16 default: 12 | any | ≥1.0.1
aes_256_ccm | 32 | 7-13 | any | even 4-16 default: 12 | any | ≥1.0.1
aes_128_gcm | 16 | ≥1 | any | 1-16 default: 16 | any | ≥1.0.1
aes_192_gcm | 24 | ≥1 | any | 1-16 default: 16 | any | ≥1.0.1
aes_256_gcm | 32 | ≥1 | any | 1-16 default: 16 | any | ≥1.0.1
chacha20_poly1305 | 32 | 1-16 | any | 16 | any | ≥1.1.0
sm4_gcm | 16 | 12 | any | 16 | any | ≥3.1.0
sm4_ccm | 16 | 12 | any | 16 | any | ≥3.1.0

Table: AEAD ciphers

Message Authentication Codes (MACs)

To be used in mac/4 and related functions.

CMAC

CMAC with the following ciphers are available with OpenSSL 1.0.1 or later if not disabled by configuration.

To dynamically check availability, check that the name cmac is present in the list returned by crypto:supports(macs). Also check that the name in the Cipher and Mode column is present in the list returned by crypto:supports(ciphers).

Cipher and Mode | Key length [bytes] | Max Mac Length (= default length) [bytes]
aes_128_cbc | 16 | 16
aes_192_cbc | 24 | 16
aes_256_cbc | 32 | 16
aes_128_ecb | 16 | 16
aes_192_ecb | 24 | 16
aes_256_ecb | 32 | 16
blowfish_cbc | 16 | 8
blowfish_ecb | 16 | 8
des_cbc | 8 | 8
des_ecb | 8 | 8
des_ede3_cbc | 24 | 8
rc2_cbc | 16 | 8

Table: CMAC cipher key lengths

HMAC

Available in all OpenSSL compatible with Erlang CRYPTO if not disabled by configuration.

To dynamically check availability, check that the name hmac is present in the list returned by crypto:supports(macs) and that the hash name is present in the list returned by crypto:supports(hashs).

Hash | Max Mac Length (= default length) [bytes]
sha | 20
sha224 | 28
sha256 | 32
sha384 | 48
sha512 | 64
sha512_224 | 28
sha512_256 | 32
sha3_224 | 28
sha3_256 | 32
sha3_384 | 48
sha3_512 | 64
shake128 | 64
shake256 | 64
blake2b | 64
blake2s | 32
md4 | 16
md5 | 16
ripemd160 | 20

Table: HMAC output sizes

POLY1305

POLY1305 is available with OpenSSL 1.1.1 or later if not disabled by configuration.

To dynamically check availability, check that the name poly1305 is present in the list returned by crypto:supports(macs).

The poly1305 mac wants an 32 bytes key and produces a 16 byte MAC by default.

Hash

To dynamically check availability, check that the wanted name in the Names column is present in the list returned by crypto:supports(hashs).

Type | Names | Limited to OpenSSL versions
SHA1 | sha |
SHA2 | sha224, sha256, sha384, sha512, sha512_224, sha512_256 |
SHA3 | sha3_224, sha3_256, sha3_384, sha3_512, shake128, shake256 | ≥1.1.1
SM3 | sm3 | ≥1.1.1
MD4 | md4 |
MD5 | md5 |
RIPEMD | ripemd160 |

Public Key Cryptography

RSA

RSA is available with all OpenSSL versions compatible with Erlang CRYPTO if not disabled by configuration. To dynamically check availability, check that the atom rsa is present in the list returned by crypto:supports(public_keys).

Warning

The RSA options are experimental.

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

Option | sign/verify | public encrypt | private encrypt
|  | private decrypt | public decrypt
{rsa_padding,rsa_x931_padding} | x |  | x
{rsa_padding,rsa_pkcs1_padding} | x | x | x
{rsa_padding,rsa_pkcs1_pss_padding} | x (2) |  |
{rsa_pss_saltlen, -2..} | x (2) |  |
{rsa_mgf1_md, atom()} | x (2) |  |
{rsa_padding,rsa_pkcs1_oaep_padding} |  | x (2) |
{rsa_mgf1_md, atom()} |  | x (2) |
{rsa_oaep_label, binary()}} |  | x (3) |
{rsa_oaep_md, atom()} |  | x (3) |
{rsa_padding,rsa_no_padding} | x (1) |  |

Notes:

OpenSSL ≤ 1.0.0

OpenSSL ≥ 1.0.1

OpenSSL ≥ 1.1.0

DSS

DSS is available with OpenSSL versions compatible with Erlang CRYPTO if not disabled by configuration. To dynamically check availability, check that the atom dss is present in the list returned by crypto:supports(public_keys).

ECDSA

ECDSA is available with OpenSSL 0.9.8o or later if not disabled by configuration. To dynamically check availability, check that the atom ecdsa is present in the list returned by crypto:supports(public_keys). If the atom ec_gf2m also is present, the characteristic two field curves are available.

The actual supported named curves could be checked by examining the list returned by crypto:supports(curves).

EdDSA

EdDSA is available with OpenSSL 1.1.1 or later if not disabled by configuration. To dynamically check availability, check that the atom eddsa is present in the list returned by crypto:supports(public_keys).

Support for the curves ed25519 and ed448 is implemented. The actual supported named curves could be checked by examining the list with the list returned by crypto:supports(curves).

Diffie-Hellman

Diffie-Hellman computations are available with OpenSSL versions compatible with Erlang CRYPTO if not disabled by configuration. To dynamically check availability, check that the atom dh is present in the list returned by crypto:supports(public_keys).

Elliptic Curve Diffie-Hellman

Elliptic Curve Diffie-Hellman is available with OpenSSL 0.9.8o or later if not disabled by configuration. To dynamically check availability, check that the atom ecdh is present in the list returned by crypto:supports(public_keys).

The Edward curves x25519 and x448 are supported with OpenSSL 1.1.1 or later if not disabled by configuration.

The actual supported named curves could be checked by examining the list returned by crypto:supports(curves).

New and Old API

This chapter describes the new api to encryption and decryption.

Background

The CRYPTO app has evolved during its lifetime. Since also the OpenSSL cryptolib has changed the API several times, there are parts of the CRYPTO app that uses a very old one internally and other parts that uses the latest one. The internal definitions of e.g cipher names was a bit hard to maintain.

It turned out that using the old api in the new way (more about that later), and still keep it backwards compatible, was not possible. Specially as more precision in the error messages is desired it could not be combined with the old standard.

Therefore the old api (see next section) is kept for now but internally implemented with new primitives.

The old API

The old functions - deprecated from 23.0 and removed from OTP 24.0 - are for ciphers:

block_encrypt/3

block_encrypt/4

block_decrypt/3

block_decrypt/4

stream_init/2

stream_init/3

stream_encrypt/2

stream_decrypt/2

next_iv/2

next_iv/3

for lists of supported algorithms:

supports/0

and for MACs (Message Authentication Codes):

cmac/3

cmac/4

hmac/3

hmac/4

hmac_init/2

hmac_update/2

hmac_final/1

hmac_final_n/2

poly1305/2

The new API

Encryption and decryption

The new functions for encrypting or decrypting one single binary are:

crypto_one_time/4

crypto_one_time/5

crypto_one_time_aead/6

crypto_one_time_aead/7

In those functions the internal crypto state is first created and initialized with the cipher type, the key and possibly other data. Then the single binary is encrypted or decrypted, the crypto state is de-allocated and the result of the crypto operation is returned.

The crypto_one_time_aead functions are for the ciphers of mode ccm or gcm, and for the cipher chacha20-poly1305.

For repeated encryption or decryption of a text divided in parts, where the internal crypto state is initialized once, and then many binaries are encrypted or decrypted with the same state, the functions are:

crypto_init/4

crypto_init/3

crypto_update/2

crypto_final/1

The crypto_init initialies an internal cipher state, and one or more calls of crypto_update does the actual encryption or decryption. Note that AEAD ciphers can't be handled this way due to their nature.

An example of where those functions are needed, is when handling the TLS protocol.

If padding was not enabled, the call to crypto_final/1 may be excluded.

For information about available algorithms, use:

supports/1

hash_info/1

cipher_info/1

The next_iv/2 and next_iv/3 are not needed since the crypto_init and crypto_update includes this functionality.

MACs (Message Authentication Codes)

The new functions for calculating a MAC of a single piece of text are:

mac/3

mac/4

macN/4

macN/5

For calculating a MAC of a text divided in parts use:

mac_init/2

mac_init/3

mac_update/2

mac_final/1

mac_finalN/2

Examples of the new api

Examples of crypto_init/4 and crypto_update/2

The functions crypto_init/4 and crypto_update/2 are intended to be used for encrypting or decrypting a sequence of blocks. First one call of crypto_init/4 initialises the crypto context. One or more calls crypto_update/2 does the actual encryption or decryption for each block.

This example shows first the encryption of two blocks and then decryptions of the cipher text, but divided into three blocks just to show that it is possible to divide the plain text and cipher text differently for some ciphers:

	1> application:start(crypto).
	ok
	2> Key = <<1:128>>.
	<<0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1>>
	3> IV = <<0:128>>.
	<<0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0>>
	4> StateEnc = crypto:crypto_init(aes_128_ctr, Key, IV, true). % encrypt -> true
	#Ref<0.3768901617.1128660993.124047>
	5> crypto:crypto_update(StateEnc, <<"First bytes">>).
	<<67,44,216,166,25,130,203,5,66,6,162>>
	6> crypto:crypto_update(StateEnc, <<"Second bytes">>).
	<<16,79,94,115,234,197,94,253,16,144,151,41>>
	7>
	7> StateDec = crypto:crypto_init(aes_128_ctr, Key, IV, false). % decrypt -> false
	#Ref<0.3768901617.1128660994.124255>
	8> crypto:crypto_update(StateDec, <<67,44,216,166,25,130,203>>).
	<<"First b">>
	9> crypto:crypto_update(StateDec, <<5,66,6,162,16,79,94,115,234,197,
        94,253,16,144,151>>).
	<<"ytesSecond byte">>
	10> crypto:crypto_update(StateDec, <<41>>).
	<<"s">>
	11>

Note that the internal data that the StateEnc and StateDec references are destructivly updated by the calls to crypto_update/2. This is to gain time in the calls of the nifs interfacing the cryptolib. In a loop where the state is saved in the loop's state, it also saves one update of the loop state per crypto operation.

For example, a simple server receiving text parts to encrypt and send the result back to the one who sent them (the Requester):

	encode(Crypto, Key, IV) ->
	crypto_loop(crypto:crypto_init(Crypto, Key, IV, true)).

	crypto_loop(State) ->
	receive
        {Text, Requester} ->
        Requester ! crypto:crypto_update(State, Text),
	loop(State)
	end.

Example of crypto_one_time/5

The same example as in the previous section, but now with one call to crypto_one_time/5:

	1> Key = <<1:128>>.
	<<0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1>>
	2> IV = <<0:128>>.
	<<0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0>>
	3> Txt = [<<"First bytes">>,<<"Second bytes">>].
	[<<"First bytes">>,<<"Second bytes">>]
	4> crypto:crypto_one_time(aes_128_ctr, Key, IV, Txt, true).
	<<67,44,216,166,25,130,203,5,66,6,162,16,79,94,115,234,
	197,94,253,16,144,151,41>>
	5>

The [<<"First bytes">>,<<"Second bytes">>] could of course have been one single binary: <<"First bytesSecond bytes">>.

Example of crypto_one_time_aead/6

The same example as in the previous section, but now with one call to crypto_one_time_aead/6:

	1> Key = <<1:128>>.
	<<0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1>>
	2> IV = <<0:128>>.
	<<0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0>>
	3> Txt = [<<"First bytes">>,<<"Second bytes">>].
	[<<"First bytes">>,<<"Second bytes">>]
	4> AAD = <<"Some additional auth data">>.
	<<"Some additional auth data">>
	5> crypto:crypto_one_time_aead(aes_128_gcm, Key, IV, Txt, AAD, true).
	{<<240,130,38,96,130,241,189,52,3,190,179,213,132,1,72,
	192,103,176,90,104,15,71,158>>,
	<<131,47,45,91,142,85,9,244,21,141,214,71,31,135,2,155>>}
	6>

The [<<"First bytes">>,<<"Second bytes">>] could of course have been one single binary: <<"First bytesSecond bytes">>.

Example of mac_init mac_update and mac_final

	1> Key = <<1:128>>.
	<<0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1>>
	2> StateMac = crypto:mac_init(cmac, aes_128_cbc, Key).
	#Ref<0.2424664121.2781478916.232610>
	3> crypto:mac_update(StateMac, <<"First bytes">>).
	#Ref<0.2424664121.2781478916.232610>
	4> crypto:mac_update(StateMac, " ").
	#Ref<0.2424664121.2781478916.232610>
	5> crypto:mac_update(StateMac, <<"last bytes">>).
	#Ref<0.2424664121.2781478916.232610>
	6> crypto:mac_final(StateMac).
	<<68,191,219,128,84,77,11,193,197,238,107,6,214,141,160,
	249>>
	7>

and compare the result with a single calculation just for this example:

	7> crypto:mac(cmac, aes_128_cbc, Key, "First bytes last bytes").
	<<68,191,219,128,84,77,11,193,197,238,107,6,214,141,160,
	249>>
	8> v(7) == v(6).
	true
	9>

Retired cipher names

This table lists the retired cipher names in the first column and suggests names to replace them with in the second column.

The new names follows the OpenSSL libcrypto names. The format is ALGORITM_KEYSIZE_MODE.

Examples of algorithms are aes, chacha20 and des. The keysize is the number of bits and examples of the mode are cbc, ctr and gcm. The mode may be followed by a number depending on the mode. An example is the ccm mode which has a variant called ccm8 where the so called tag has a length of eight bits.

The old names had by time lost any common naming convention which the new names now introduces. The new names include the key length which improves the error checking in the lower levels of the crypto application.

Instead of: | Use:
aes_cbc128 | aes_128_cbc
aes_cbc256 | aes_256_cbc
aes_cbc | aes_128_cbc, aes_192_cbc, aes_256_cbc
aes_ccm | aes_128_ccm, aes_192_ccm, aes_256_ccm
aes_cfb128 | aes_128_cfb128, aes_192_cfb128, aes_256_cfb128
aes_cfb8 | aes_128_cfb8, aes_192_cfb8, aes_256_cfb8
aes_ctr | aes_128_ctr, aes_192_ctr, aes_256_ctr
aes_gcm | aes_128_gcm, aes_192_gcm, aes_256_gcm
des3_cbc | des_ede3_cbc
des3_cbf | des_ede3_cfb
des3_cfb | des_ede3_cfb
des_ede3 | des_ede3_cbc
des_ede3_cbf | des_ede3_cfb

crypto

Crypto Functions

This module provides a set of cryptographic functions.

Hash functions -

SHA1, SHA2 - Secure Hash Standard (FIPS PUB180-4)

SHA3 - SHA-3 Standard: Permutation-Based Hash and Extendable-Output Functions (FIPS PUB 202)

BLAKE2 - BLAKE2 — fast secure hashing

SM3 - The SM3 Hash Function (GM/T 0004-2012)

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)

SM4 - The SM4 Block Cipher Algorithm

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.

Enabling FIPS mode will also disable algorithms and features.

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

Exceptions

Atoms - the older style

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

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

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

3-tuples - the new style

The exception is:

error:{Tag, C_FileInfo, Description}

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

The exception tags are:

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

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

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

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

To catch the exception, use for example:

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

Summary

Types: Ciphers

cipher()

cipher_aead()

Ciphers known by the CRYPTO application.

cipher_iv()

cipher_no_iv()

crypto_opt()

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

crypto_opts()

Equivalent to crypto_opt().

cryptolib_padding()

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

otp_padding()

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

padding()

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

Types: Diffie-Hellman Keys and parameters

dh_params()

dh_private()

dh_public()

Equivalent to dh_private().

ecdh_params()

ecdh_private()

Equivalent to ecdh_params().

ecdh_public()

Equivalent to ecdh_params().

Types: Digests and hash

blake2()

cmac_cipher_algorithm()

compatibility_only_hash()

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

dss_digest_type()

ecdsa_digest_type()

hash_algorithm()

hash_xof_algorithm()

hmac_hash_algorithm()

rsa_digest_type()

sha1()

Equivalent to blake2().

sha2()

Equivalent to blake2().

sha3()

Equivalent to blake2().

sha3_xof()

Equivalent to blake2().

Types: Elliptic Curves

ec_basis()

Curve definition details.

ec_characteristic_two_field()

Equivalent to ec_basis().

ec_curve()

Parametric curve definition.

ec_explicit_curve()

Equivalent to ec_curve().

ec_field()

Equivalent to ec_curve().

ec_named_curve()

Equivalent to edwards_curve_ed().

ec_prime_field()

Equivalent to ec_basis().

edwards_curve_dh()

Equivalent to edwards_curve_ed().

edwards_curve_ed()

Note that some curves are disabled if FIPS is enabled.

Types: Internal data types

crypto_state()

Equivalent to mac_state().

hash_state()

Equivalent to mac_state().

mac_state()

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

Types: Key Encapsulation Mechanism

kem()

Key encapsulation mechanisms.

Types: Keys

key_integer()

Always binary/0 when used as return value

Types: Public Key Ciphers

pk_encrypt_decrypt_algs()

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

pk_encrypt_decrypt_opts()

Equivalent to rsa_padding().

rsa_compat_opts()

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

rsa_opt()

Equivalent to rsa_padding().

rsa_padding()

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

Types: Public Key Sign and Verify

pk_sign_verify_algs()

Algorithms for sign and verify.

pk_sign_verify_opts()

Equivalent to rsa_sign_verify_padding().

rsa_sign_verify_opt()

Equivalent to rsa_sign_verify_padding().

rsa_sign_verify_padding()

Options for sign and verify.

Types: Public/Private Keys

dss_private()

dss_public()

Equivalent to dss_private().

ecdsa_params()

ecdsa_private()

Equivalent to ecdsa_params().

ecdsa_public()

Equivalent to ecdsa_params().

eddsa_params()

eddsa_private()

Equivalent to eddsa_params().

eddsa_public()

Equivalent to eddsa_params().

rsa_params()

rsa_private()

Equivalent to rsa_params().

rsa_public()

Equivalent to rsa_params().

srp_comp_params()

Equivalent to srp_host_comp_params().

srp_gen_params()

Equivalent to srp_host_comp_params().

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'

srp_host_gen_params()

Equivalent to srp_host_comp_params().

srp_private()

srp_public()

Equivalent to srp_private().

srp_user_comp_params()

Equivalent to srp_host_comp_params().

srp_user_gen_params()

Equivalent to srp_host_comp_params().

Types: Types for Engines

engine_cmnd()

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

engine_key_ref()

Equivalent to engine_ref().

engine_method_type()

engine_ref()

The result of a call to engine_load/3.

key_id()

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

The password of the key stored in an engine.

Types

crypto_integer()

mldsa()

mldsa_private()

mldsa_public()

rand_cache_state()

rand_plugin_aes_state()

rand_plugin_prng1_init_state()

rand_plugin_prng1_state()

rand_plugin_state()

slh_dsa()

slh_dsa_private()

slh_dsa_public()

Cipher API

crypto_final(State)

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

crypto_get_data(State)

Return information about a crypto_state/0.

crypto_init(Cipher, Key, FlagOrOptions)

Initialize the state for a streaming encryption or decryption operation.

crypto_init(Cipher, Key, IV, FlagOrOptions)

Initialize the state for a streaming encryptions or decryptions operation.

crypto_one_time(Cipher, Key, Data, FlagOrOptions)

Do a complete encrypt or decrypt of the full text.

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

Do a complete encrypt or decrypt of the full text.

crypto_one_time_aead(State, IV, InText, AAD)

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

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

Do a complete encrypt with an AEAD cipher of the full text with the default tag length.

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

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

crypto_one_time_aead_init(Cipher, Key, TagLength, EncFlag)

Initializes AEAD cipher.

crypto_update(State, Data)

Add data to a streaming encryption or decryption operation.

Deprecated API

enable_fips_mode(Enable) deprecated

Enable or disable FIPs mode.

start() deprecated

Use application:start(crypto) instead.

stop() deprecated

Use application:stop(crypto) instead.

Engine API

engine_add(Engine)

Add the engine to OpenSSL's internal list.

engine_by_id(EngineId)

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

engine_ctrl_cmd_string(Engine, CmdName, CmdArg)

Send ctrl commands to an OpenSSL engine.

engine_ctrl_cmd_string(Engine, CmdName, CmdArg, Optional)

Send ctrl commands to an OpenSSL engine.

engine_get_all_methods()

Return a list of all possible engine methods.

engine_get_id(Engine)

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

engine_get_name(Engine)

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

engine_list()

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

engine_load(EngineId, PreCmds, PostCmds)

Load an OpenSSL engine.

engine_register(Engine, EngineMethods)

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

engine_remove(Engine)

Remove the engine from OpenSSL's internal list.

engine_unload(Engine)

Unload an OpenSSL engine.

engine_unregister(Engine, EngineMethods)

Unregister engine so it does not handle some type of methods.

ensure_engine_loaded(EngineId, LibPath)

Load a dynamic engine if not already done.

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

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

privkey_to_pubkey(Type, EnginePrivateKeyRef)

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

Hash API

hash(Type, Data)

Compute a message digest.

hash_final(State)

Finalize a streaming hash calculation.

hash_init(Type)

Initialize the state for a streaming hash digest calculation.

hash_update(State, Data)

Add data to a streaming digest calculation.

hash_xof(Type, Data, Length)

Compute a message digest for an xof_algorithm.

Key API

compute_key(Type, OthersPublicKey, MyPrivateKey, Params)

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

decapsulate_key(Type, MyPrivKey, EncapSecret)

Regenerate shared secret from encapsulated secret and private key.

encapsulate_key(Type, OthersPublicKey)

Generate encapsulated shared secret from the other party's public key.

generate_key(Type, Params)

Equivalent to generate_key/3.

generate_key(Type, Params, PrivKeyIn)

Generate a public key.

Legacy RSA Encryption API

private_decrypt(Algorithm, CipherText, PrivateKey, Options)

Decrypt using a private key.

private_encrypt(Algorithm, PlainText, PrivateKey, Options)

Encrypt using a private key.

public_decrypt(Algorithm, CipherText, PublicKey, Options)

Decrypt using a public key.

public_encrypt(Algorithm, PlainText, PublicKey, Options)

Encrypt using a public key.

MAC API

mac(Type, Key, Data)

Compute a poly1305 MAC (Message Authentication Code).

mac(Type, SubType, Key, Data)

Compute a MAC (Message Authentication Code).

mac_final(State)

Finalize a streaming MAC operation.

mac_finalN(State, MacLength)

Finalize a MAC operation with a custom length.

mac_init(Type, Key)

Initialize a state for streaming poly1305 MAC calculation.

mac_init(Type, SubType, Key)

Initialize the state for streaming MAC calculation.

mac_update(State0, Data)

Add data to a streaming MAC calculation.

macN(Type, Key, Data, MacLength)

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

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

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

Plug-In Generators

rand_seed()

Create a generator for rand and save it in the process dictionary.

rand_seed_alg(Alg)

Create a generator for rand with specified algorithm, and save it in the process dictionary.

rand_seed_alg(Alg, Seed)

Create and seed a generator for rand with specified algorithm, and save it in the process dictionary.

rand_seed_alg_s/1

Create a generator for rand with specified algorithm.

rand_seed_alg_s(Alg, Seed)

Create and seed a generator for rand with specified algorithm.

rand_seed_s()

Create a generator for rand.

Random API

rand_seed(Seed)

Mixes in the bytes of the given binary into the internal state of OpenSSL's random number generator.

rand_uniform/2 deprecated

Generate a random integer number.

strong_rand_bytes(N)

Generate bytes with randomly uniform values 0..255.

strong_rand_range/1

Generate a random integer in a specified range.

Sign/Verify API

sign(Algorithm, DigestType, Msg, Key)

Equivalent to sign/5.

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

Create a digital signature.

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

Equivalent to verify/6.

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

Verify a digital signature.

Utility Functions

bytes_to_integer(Bin)

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

cipher_info(Type)

Get information about a cipher algorithm.

ec_curve(CurveName)

Return the defining parameters of a elliptic curve.

ec_curves()

Return all supported named elliptic curves.

exor(Bin1, Bin2)

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

hash_equals(BinA, BinB)

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

hash_info(Type)

Get information about a hash algorithm.

info()

Get information about crypto and the OpenSSL backend.

info_fips()

Get information about the operating status of FIPS.

info_lib()

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

mod_pow(N, P, M)

Compute the function N^P mod M.

supports(Type)

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

Types: Ciphers

cipher()

(not exported)

-type cipher() :: cipher_no_iv() | cipher_iv() | cipher_aead().

cipher_aead()

(not exported)

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

Ciphers known by the CRYPTO application.

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

cipher_iv()

(not exported)

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

cipher_no_iv()

(not exported)

-type cipher_no_iv() ::
          aes_128_ecb | aes_192_ecb | aes_256_ecb | aes_ecb | blowfish_ecb | des_ecb | sm4_ecb | rc4.

crypto_opt()

(not exported)

-type crypto_opt() :: {encrypt, boolean()} | {padding, padding()}.

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

crypto_opts()

(not exported)

-type crypto_opts() :: boolean() | [crypto_opt()].

Equivalent to crypto_opt().

cryptolib_padding()

(not exported)

-type cryptolib_padding() :: none | pkcs_padding.

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

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

otp_padding()

(not exported)

-type otp_padding() :: zero | random.

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

padding()

(not exported)

-type padding() :: cryptolib_padding() | otp_padding().

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

Types: Diffie-Hellman Keys and parameters

dh_params()

(not exported)

-type dh_params() :: [key_integer()].

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

dh_private()

-type dh_private() :: key_integer().

dh_public()

-type dh_public() :: key_integer().

Equivalent to dh_private().

ecdh_params()

(not exported)

-type ecdh_params() :: ec_named_curve() | edwards_curve_dh() | ec_explicit_curve().

ecdh_private()

(not exported)

-type ecdh_private() :: key_integer().

Equivalent to ecdh_params().

ecdh_public()

(not exported)

-type ecdh_public() :: key_integer().

Equivalent to ecdh_params().

Types: Digests and hash

blake2()

(not exported)

-type blake2() :: blake2b | blake2s.

cmac_cipher_algorithm()

-type cmac_cipher_algorithm() ::
          aes_128_cbc | aes_192_cbc | aes_256_cbc | aes_cbc | blowfish_cbc | des_cbc | des_ede3_cbc |
          rc2_cbc.

compatibility_only_hash()

(not exported)

-type compatibility_only_hash() :: md5 | md4.

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

dss_digest_type()

-type dss_digest_type() :: sha1() | sha2().

ecdsa_digest_type()

-type ecdsa_digest_type() :: sha1() | sha2().

hash_algorithm()

(not exported)

-type hash_algorithm() ::
          sha1() | sha2() | sha3() | sha3_xof() | blake2() | ripemd160 | sm3 | compatibility_only_hash().

hash_xof_algorithm()

(not exported)

-type hash_xof_algorithm() :: sha3_xof().

hmac_hash_algorithm()

-type hmac_hash_algorithm() :: sha1() | sha2() | sha3() | sm3 | compatibility_only_hash().

rsa_digest_type()

-type rsa_digest_type() :: sha1() | sha2() | md5 | ripemd160.

sha1()

-type sha1() :: sha.

Equivalent to blake2().

sha2()

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

Equivalent to blake2().

sha3()

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

Equivalent to blake2().

sha3_xof()

(not exported)

-type sha3_xof() :: shake128 | shake256.

Equivalent to blake2().

Types: Elliptic Curves

ec_basis()

(not exported)

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

Curve definition details.

ec_characteristic_two_field()

(not exported)

-type ec_characteristic_two_field() :: {characteristic_two_field, M :: integer(), Basis :: ec_basis()}.

Equivalent to ec_basis().

ec_curve()

(not exported)

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

Parametric curve definition.

ec_explicit_curve()

(not exported)

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

Equivalent to ec_curve().

ec_field()

(not exported)

-type ec_field() :: ec_prime_field() | ec_characteristic_two_field().

Equivalent to ec_curve().

ec_named_curve()

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

Equivalent to edwards_curve_ed().

ec_prime_field()

(not exported)

-type ec_prime_field() :: {prime_field, Prime :: integer()}.

Equivalent to ec_basis().

edwards_curve_dh()

(not exported)

-type edwards_curve_dh() :: x25519 | x448.

Equivalent to edwards_curve_ed().

edwards_curve_ed()

(not exported)

-type edwards_curve_ed() :: ed25519 | ed448.

Note that some curves are disabled if FIPS is enabled.

Types: Internal data types

crypto_state()

-opaque crypto_state()

Equivalent to mac_state().

hash_state()

-opaque hash_state()

Equivalent to mac_state().

mac_state()

-opaque mac_state()

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

Types: Key Encapsulation Mechanism

kem()

-type kem() :: mlkem512 | mlkem768 | mlkem1024.

Key encapsulation mechanisms.

Types: Keys

key_integer()

(not exported)

-type key_integer() :: integer() | binary().

Always binary/0 when used as return value

Types: Public Key Ciphers

pk_encrypt_decrypt_algs()

(not exported)

-type pk_encrypt_decrypt_algs() :: rsa.

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

pk_encrypt_decrypt_opts()

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

Equivalent to rsa_padding().

rsa_compat_opts()

(not exported)

-type rsa_compat_opts() :: [{rsa_pad, rsa_padding()}] | rsa_padding().

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

rsa_opt()

(not exported)

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

Equivalent to rsa_padding().

rsa_padding()

(not exported)

-type rsa_padding() :: rsa_pkcs1_padding | rsa_pkcs1_oaep_padding | rsa_x931_padding | rsa_no_padding.

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

Warning

The RSA options are experimental.

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

Types: Public Key Sign and Verify

pk_sign_verify_algs()

(not exported)

-type pk_sign_verify_algs() :: rsa | dss | ecdsa | eddsa | mldsa() | slh_dsa().

Algorithms for sign and verify.

pk_sign_verify_opts()

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

Equivalent to rsa_sign_verify_padding().

rsa_sign_verify_opt()

(not exported)

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

Equivalent to rsa_sign_verify_padding().

rsa_sign_verify_padding()

(not exported)

-type rsa_sign_verify_padding() ::
          rsa_pkcs1_padding | rsa_pkcs1_pss_padding | rsa_x931_padding | rsa_no_padding.

Options for sign and verify.

Warning

The RSA options are experimental.

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

Types: Public/Private Keys

dss_private()

(not exported)

-type dss_private() :: [key_integer()].

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

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

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

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

dss_public()

(not exported)

-type dss_public() :: [key_integer()].

Equivalent to dss_private().

ecdsa_params()

(not exported)

-type ecdsa_params() :: ec_named_curve() | ec_explicit_curve().

ecdsa_private()

(not exported)

-type ecdsa_private() :: key_integer().

Equivalent to ecdsa_params().

ecdsa_public()

(not exported)

-type ecdsa_public() :: key_integer().

Equivalent to ecdsa_params().

eddsa_params()

(not exported)

-type eddsa_params() :: edwards_curve_ed().

eddsa_private()

(not exported)

-type eddsa_private() :: key_integer().

Equivalent to eddsa_params().

eddsa_public()

(not exported)

-type eddsa_public() :: key_integer().

Equivalent to eddsa_params().

rsa_params()

(not exported)

-type rsa_params() :: {ModulusSizeInBits :: integer(), PublicExponent :: key_integer()}.

rsa_public() = [E, N]

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

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

rsa_private()

(not exported)

-type rsa_private() :: [key_integer()].

Equivalent to rsa_params().

rsa_public()

(not exported)

-type rsa_public() :: [key_integer()].

Equivalent to rsa_params().

srp_comp_params()

(not exported)

-type srp_comp_params() :: {user, srp_user_comp_params()} | {host, srp_host_comp_params()}.

Equivalent to srp_host_comp_params().

srp_gen_params()

(not exported)

-type srp_gen_params() :: {user, srp_user_gen_params()} | {host, srp_host_gen_params()}.

Equivalent to srp_host_comp_params().

srp_host_comp_params()

(not exported)

-type srp_host_comp_params() :: [binary() | atom()].

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

srp_host_gen_params()

(not exported)

-type srp_host_gen_params() :: [binary() | atom() | list()].

Equivalent to srp_host_comp_params().

srp_private()

(not exported)

-type srp_private() :: key_integer().

srp_public() = key_integer()

Where is A or B from SRP design

srp_private() = key_integer()

Where is a or b from SRP design

srp_public()

(not exported)

-type srp_public() :: key_integer().

Equivalent to srp_private().

srp_user_comp_params()

(not exported)

-type srp_user_comp_params() :: [binary() | atom()].

Equivalent to srp_host_comp_params().

srp_user_gen_params()

(not exported)

-type srp_user_gen_params() :: [binary() | atom() | list()].

Equivalent to srp_host_comp_params().

Types: Types for Engines

engine_cmnd()

(not exported)

-type engine_cmnd() :: {unicode:chardata(), unicode:chardata()}.

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

engine_key_ref()

(not exported)

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

Equivalent to engine_ref().

engine_method_type()

(not exported)

-type engine_method_type() ::
          engine_method_rsa | engine_method_dsa | engine_method_dh | engine_method_rand |
          engine_method_ecdh | engine_method_ecdsa | engine_method_ciphers | engine_method_digests |
          engine_method_store | engine_method_pkey_meths | engine_method_pkey_asn1_meths |
          engine_method_ec.

engine_ref()

-type engine_ref() :: term().

The result of a call to engine_load/3.

key_id()

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

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

password()

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

The password of the key stored in an engine.

Types

crypto_integer()

(not exported)

-type crypto_integer() :: binary() | integer().

mldsa()

-type mldsa() :: mldsa44 | mldsa65 | mldsa87.

mldsa_private()

(not exported)

-type mldsa_private() :: {seed | expandedkey, binary()}.

mldsa_public()

(not exported)

-type mldsa_public() :: binary().

rand_cache_state()

(not exported)

-type rand_cache_state() :: binary().

rand_plugin_aes_state()

(not exported)

-type rand_plugin_aes_state() :: dynamic().

rand_plugin_prng1_init_state()

(not exported)

-type rand_plugin_prng1_init_state() :: {cipher_iv(), binary(), binary(), binary()}.

rand_plugin_prng1_state()

(not exported)

-type rand_plugin_prng1_state() ::
          rand_plugin_prng1_init_state() | maybe_improper_list(binary(), {crypto_state(), binary()}).

rand_plugin_state()

(not exported)

-type rand_plugin_state() :: no_state.

slh_dsa()

-type slh_dsa() ::
          slh_dsa_shake_128s | slh_dsa_shake_128f | slh_dsa_sha2_128s | slh_dsa_sha2_128f |
          slh_dsa_shake_192s | slh_dsa_shake_192f | slh_dsa_sha2_192s | slh_dsa_sha2_192f |
          slh_dsa_shake_256s | slh_dsa_shake_256f | slh_dsa_sha2_256s | slh_dsa_sha2_256f.

slh_dsa_private()

(not exported)

-type slh_dsa_private() :: binary().

slh_dsa_public()

(not exported)

-type slh_dsa_public() :: binary().

Cipher API

crypto_final(State)

(since OTP 23.0)

-spec crypto_final(State) -> FinalResult when State :: crypto_state(), FinalResult :: binary().

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

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

Uses the 3-tuple style for error handling.

crypto_get_data(State)

(since OTP 23.0)

-spec crypto_get_data(State) -> Result when State :: crypto_state(), Result :: map().

Return information about a crypto_state/0.

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

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

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

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

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

Uses the 3-tuple style for error handling.

crypto_init(Cipher, Key, FlagOrOptions)

(since OTP 22.0)

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

Initialize the state for a streaming encryption or decryption operation.

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

Uses the 3-tuple style for error handling.

crypto_init(Cipher, Key, IV, FlagOrOptions)

(since OTP 22.0)

-spec crypto_init(Cipher, Key, IV, FlagOrOptions) -> State
                     when
                         Cipher :: cipher_iv(),
                         Key :: iodata(),
                         IV :: iodata(),
                         FlagOrOptions :: crypto_opts(),
                         State :: crypto_state().

Initialize the state for a streaming encryptions or decryptions operation.

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

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

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

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

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

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

The actual padding is performed by crypto_final/1.

For blocksizes call cipher_info/1.

Uses the 3-tuple style for error handling.

See examples in the User's Guide.

crypto_one_time(Cipher, Key, Data, FlagOrOptions)

(since OTP 22.0)

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

Do a complete encrypt or decrypt of the full text.

As crypto_one_time/5 but for ciphers without IVs.

Uses the 3-tuple style for error handling.

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

(since OTP 22.0)

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

Do a complete encrypt or decrypt of the full text.

Argument Data is the text to be encrypted or decrypted.

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

Uses the 3-tuple style for error handling.

See examples in the User's Guide.

crypto_one_time_aead(State, IV, InText, AAD)

(since OTP 28.0)

-spec crypto_one_time_aead(State, IV, InText, AAD) -> Result
                              when
                                  State :: crypto_state(),
                                  IV :: iodata(),
                                  InText :: iodata(),
                                  AAD :: iodata(),
                                  Result :: EncryptResult | DecryptResult,
                                  EncryptResult :: binary(),
                                  DecryptResult :: binary() | error.

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

Similar to 'crypto_one_time_aead/7' but uses the handle from 'crypto_one_time_aead_init/4'.

Appends the tag of the specified 'TagLength' to the end of the encrypted data, when doing encryption. Strips the tag from the end of 'InText' and verifies it when doing decryption.

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

(since OTP 22.0)

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

Do a complete encrypt with an AEAD cipher of the full text with the default tag length.

Equivalent to crypto_one_time_aead(Cipher, Key, IV, InText, AAD, TagLength, true) where TagLength is the default tag length for the given Cipher.

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

(since OTP 22.0)

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

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

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

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

Warning

The length of the tag at decryption is not checked by the function. It is the caller's responsibility to ensure that the length of the tag matches the length of the tag used when the data was encrypted. Otherwise the decryption may succeed if the given tag only matches the start of the proper tag.

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

Uses the 3-tuple style for error handling.

See examples in the User's Guide.

crypto_one_time_aead_init(Cipher, Key, TagLength, EncFlag)

(since OTP 28.0)

-spec crypto_one_time_aead_init(Cipher, Key, TagLength, EncFlag) -> Result
                                   when
                                       Cipher :: cipher_aead(),
                                       Key :: iodata(),
                                       TagLength :: non_neg_integer(),
                                       EncFlag :: boolean(),
                                       Result :: crypto_state().

Initializes AEAD cipher.

Similar to 'crypto_one_time_aead/7' but only does the initialization part, returns a handle that can be used with 'crypto_one_time_aead/4' serveral times.

crypto_update(State, Data)

(since OTP 22.0)

-spec crypto_update(State, Data) -> Result
                       when State :: crypto_state(), Data :: iodata(), Result :: binary().

Add data to a streaming encryption or decryption operation.

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

Uses the 3-tuple style for error handling.

See examples in the User's Guide.

Deprecated API

enable_fips_mode(Enable)

(since OTP 21.1)

This function is deprecated. crypto:enable_fips_mode/1 is deprecated; use config parameter fips_mode.

-spec enable_fips_mode(Enable) -> Result when Enable :: boolean(), Result :: boolean().

Enable or disable FIPs mode.

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

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

See also info_fips/0.

start()

This function is deprecated. crypto:start/0 is deprecated; use application:start(crypto) instead.

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

Use application:start(crypto) instead.

Warning

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

stop()

This function is deprecated. crypto:stop/0 is deprecated; use application:stop(crypto) instead.

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

Use application:stop(crypto) instead.

Engine API

engine_add(Engine)

(since OTP 21.0.6)

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

Add the engine to OpenSSL's internal list.

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

engine_by_id(EngineId)

(since OTP 21.0.6)

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

Get a reference to an already loaded engine with EngineId. An error tuple is returned if the engine cannot 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)

(since OTP 20.2)

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

Send ctrl commands to an OpenSSL engine.

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

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

engine_ctrl_cmd_string(Engine, CmdName, CmdArg, Optional)

(since OTP 20.2)

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

Send ctrl commands to an OpenSSL engine.

Optional is a boolean argument that can relax the semantics of the function. If set to true it will only return failure if the ENGINE supported the given command name but failed while executing it, if the ENGINE does not 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_get_all_methods()

(since OTP 20.2)

-spec engine_get_all_methods() -> Result when Result :: [engine_method_type()].

Return a list of all possible engine methods.

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

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

engine_get_id(Engine)

(since OTP 21.0.6)

-spec engine_get_id(Engine) -> EngineId when Engine :: engine_ref(), EngineId :: unicode:chardata().

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

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

engine_get_name(Engine)

(since OTP 21.0.6)

-spec engine_get_name(Engine) -> EngineName
                         when Engine :: engine_ref(), EngineName :: unicode:chardata().

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

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

engine_list()

(since OTP 20.2)

-spec engine_list() -> Result when Result :: [EngineId :: unicode:chardata()].

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

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

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

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

engine_load(EngineId, PreCmds, PostCmds)

(since OTP 20.2)

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

Load an OpenSSL engine.

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

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

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

engine_register(Engine, EngineMethods)

(since OTP 25.1)

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

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

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

engine_remove(Engine)

(since OTP 21.0.6)

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

Remove the engine from OpenSSL's internal list.

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

engine_unload(Engine)

(since OTP 20.2)

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

Unload an OpenSSL engine.

Unloads the OpenSSL engine given by Engine. An error tuple is returned if the engine cannot 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_unregister(Engine, EngineMethods)

(since OTP 25.1)

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

Unregister engine so it does not handle some type of methods.

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

ensure_engine_loaded(EngineId, LibPath)

(since OTP 21.0.6)

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

Load a dynamic engine if not already done.

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

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

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

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

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

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

(since OTP 24.2)

-spec pbkdf2_hmac(Digest, Pass, Salt, Iter, KeyLen) -> Result
                     when
                         Digest :: sha | sha224 | sha256 | sha384 | sha512 | sha512_224 | sha512_256,
                         Pass :: binary(),
                         Salt :: binary(),
                         Iter :: pos_integer(),
                         KeyLen :: pos_integer(),
                         Result :: binary().

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

Uses the 3-tuple style for error handling.

privkey_to_pubkey(Type, EnginePrivateKeyRef)

(since OTP 20.2)

-spec privkey_to_pubkey(Type, EnginePrivateKeyRef) -> PublicKey
                           when
                               Type :: rsa | dss,
                               EnginePrivateKeyRef :: engine_key_ref(),
                               PublicKey :: rsa_public() | dss_public().

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

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

Hash API

hash(Type, Data)

(since OTP R15B02)

-spec hash(Type, Data) -> Digest when Type :: hash_algorithm(), Data :: iodata(), Digest :: binary().

Compute a message digest.

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

Uses the 3-tuple style for error handling.

hash_final(State)

(since OTP R15B02)

-spec hash_final(State) -> Digest when State :: hash_state(), Digest :: binary().

Finalize a streaming hash calculation.

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

Uses the 3-tuple style for error handling.

hash_init(Type)

(since OTP R15B02)

-spec hash_init(Type) -> State when Type :: hash_algorithm(), State :: hash_state().

Initialize the state for a streaming hash digest calculation.

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

Uses the 3-tuple style for error handling.

hash_update(State, Data)

(since OTP R15B02)

-spec hash_update(State, Data) -> NewState
                     when State :: hash_state(), NewState :: hash_state(), Data :: iodata().

Add data to a streaming digest calculation.

Update the digest using the given Data of any length.

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

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

Uses the 3-tuple style for error handling.

hash_xof(Type, Data, Length)

(since OTP 26.0)

-spec hash_xof(Type, Data, Length) -> Digest
                  when
                      Type :: hash_xof_algorithm(),
                      Data :: iodata(),
                      Length :: non_neg_integer(),
                      Digest :: binary().

Compute a message digest for an xof_algorithm.

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

Uses the 3-tuple style for error handling.

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

Key API

compute_key(Type, OthersPublicKey, MyPrivateKey, Params)

(since OTP R16B01)

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

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

See also public_key:compute_key/2.

Uses the 3-tuple style for error handling.

decapsulate_key(Type, MyPrivKey, EncapSecret)

(since OTP 28.1)

-spec decapsulate_key(Type, MyPrivKey, EncapSecret) -> Secret
                         when
                             Type :: kem(),
                             MyPrivKey :: binary(),
                             EncapSecret :: binary(),
                             Secret :: binary().

Regenerate shared secret from encapsulated secret and private key.

Returns a shared secret for encryption/decryption by local party.

Supported encapsulation methods can be obtained with supports(kems).

encapsulate_key(Type, OthersPublicKey)

(since OTP 28.1)

-spec encapsulate_key(Type, OthersPublicKey) -> {Secret, EncapSecret}
                         when
                             Type :: kem(),
                             OthersPublicKey :: binary(),
                             Secret :: binary(),
                             EncapSecret :: binary().

Generate encapsulated shared secret from the other party's public key.

Returns both a shared secret for encryption/decryption by local party and an encapsulated format of the same secret to be safely sent to the other party. With its private key, the other party can decapsulate the received secret (with decapsulate_key/3 for example) to regenerate the same shared secret.

Supported encapsulation methods can be obtained with supports(kems).

generate_key(Type, Params)

(since OTP R16B01)

-spec generate_key(Type, Params) -> {PublicKey, PrivKeyOut}
                      when
                          Type ::
                              dh | ecdh | eddh | eddsa | rsa |
                              mldsa() |
                              mlkem512 | mlkem768 | mlkem1024 |
                              slh_dsa() |
                              srp,
                          PublicKey :: dh_public() | ecdh_public() | rsa_public() | srp_public(),
                          PrivKeyOut ::
                              dh_private() |
                              ecdh_private() |
                              rsa_private() |
                              {srp_public(), srp_private()},
                          Params ::
                              dh_params() |
                              ecdh_params() |
                              eddsa_params() |
                              rsa_params() |
                              srp_gen_params() |
                              [].

Equivalent to generate_key/3.

generate_key(Type, Params, PrivKeyIn)

(since OTP R16B01)

-spec generate_key(Type, Params, PrivKeyIn) -> {PublicKey, PrivKeyOut}
                      when
                          Type ::
                              dh | ecdh | eddh | eddsa | rsa |
                              mldsa() |
                              mlkem512 | mlkem768 | mlkem1024 | srp |
                              slh_dsa(),
                          PublicKey :: dh_public() | ecdh_public() | rsa_public() | srp_public(),
                          PrivKeyIn ::
                              undefined |
                              dh_private() |
                              ecdh_private() |
                              rsa_private() |
                              {srp_public(), srp_private()},
                          PrivKeyOut ::
                              dh_private() |
                              ecdh_private() |
                              rsa_private() |
                              {srp_public(), srp_private()},
                          Params ::
                              dh_params() |
                              ecdh_params() |
                              eddsa_params() |
                              rsa_params() |
                              srp_comp_params() |
                              [].

Generate a public key.

See also public_key:generate_key/1.

Uses the 3-tuple style for error handling.

Note

If the linked version of cryptolib is OpenSSL 3.0

and the Type is dh (diffie-hellman)

and the parameter P (in dh_params/0) is one of the MODP groups (see RFC 3526)

and the optional MaxPrivateKeyBitLength parameter (in dh_params/0) is present,

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

Legacy RSA Encryption API

private_decrypt(Algorithm, CipherText, PrivateKey, Options)

(since OTP R16B01)

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

Decrypt using a private key.

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

Uses the 3-tuple style for error handling.

Warning

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

private_encrypt(Algorithm, PlainText, PrivateKey, Options)

(since OTP R16B01)

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

Encrypt using a private key.

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

Uses the 3-tuple style for error handling.

Public-key decryption using the private key. See also crypto:private_decrypt/4

Warning

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

public_decrypt(Algorithm, CipherText, PublicKey, Options)

(since OTP R16B01)

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

Decrypt using a public key.

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

Uses the 3-tuple style for error handling.

Warning

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

public_encrypt(Algorithm, PlainText, PublicKey, Options)

(since OTP R16B01)

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

Encrypt using a public key.

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

Uses the 3-tuple style for error handling.

Warning

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

MAC API

mac(Type, Key, Data)

(since OTP 22.1)

-spec mac(Type :: poly1305, Key, Data) -> Mac when Key :: iodata(), Data :: iodata(), Mac :: binary().

Compute a poly1305 MAC (Message Authentication Code).

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

Uses the 3-tuple style for error handling.

mac(Type, SubType, Key, Data)

(since OTP 22.1)

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

Compute a MAC (Message Authentication Code).

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

SubType depends on the MAC Type:

For hmac it is a hash algorithm, see Algorithm Details in the User's Guide.

For cmac it is a cipher suitable for cmac, see Algorithm Details in the User's Guide.

For poly1305 it should be set to undefined or the mac/2 function could be used instead, see Algorithm Details in the User's Guide.

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

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

Uses the 3-tuple style for error handling.

mac_final(State)

(since OTP 22.1)

-spec mac_final(State) -> Mac when State :: mac_state(), Mac :: binary().

Finalize a streaming MAC operation.

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

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

Uses the 3-tuple style for error handling.

mac_finalN(State, MacLength)

(since OTP 22.1)

-spec mac_finalN(State, MacLength) -> Mac
                    when State :: mac_state(), MacLength :: pos_integer(), Mac :: binary().

Finalize a MAC operation with a custom length.

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

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

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

Uses the 3-tuple style for error handling.

mac_init(Type, Key)

(since OTP 22.1)

-spec mac_init(Type :: poly1305, Key) -> State when Key :: iodata(), State :: mac_state().

Initialize a state for streaming poly1305 MAC calculation.

Same as mac_init(Type, undefined, Key).

Uses the 3-tuple style for error handling.

mac_init(Type, SubType, Key)

(since OTP 22.1)

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

Initialize the state for streaming MAC calculation.

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

SubType depends on the MAC Type:

For hmac it is a hash algorithm, see Algorithm Details in the User's Guide.

For cmac it is a cipher suitable for cmac, see Algorithm Details in the User's Guide.

For poly1305 it should be set to undefined or the mac/2 function could be used instead, see Algorithm Details in the User's Guide.

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

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

Uses the 3-tuple style for error handling.

See examples in the User's Guide.

mac_update(State0, Data)

(since OTP 22.1)

-spec mac_update(State0, Data) -> State
                    when Data :: iodata(), State0 :: mac_state(), State :: mac_state().

Add data to a streaming MAC calculation.

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

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

Uses the 3-tuple style for error handling.

macN(Type, Key, Data, MacLength)

(since OTP 22.1)

-spec macN(Type :: poly1305, Key, Data, MacLength) -> Mac
              when Key :: iodata(), Data :: iodata(), Mac :: binary(), MacLength :: pos_integer().

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

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

Uses the 3-tuple style for error handling.

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

(since OTP 22.1)

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

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

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

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

Plug-In Generators

rand_seed()

(since OTP 20.0)

-spec rand_seed() -> {rand:alg_handler(crypto), rand_plugin_state()}.

Create a generator for rand and save it in the process dictionary.

Equivalent to rand_seed_s/0 but also saves the returned state object (generator) in the process dictionary. That is, it is equivalent to rand:seed(rand_seed_s()).

See rand:seed/1 and rand_seed_s/0.

Example

_ = crypto:rand_seed(),
IntegerValue = rand:uniform(42), % 1 .. 42
FloatValue = rand:uniform().     % [0.0, 1.0)

Note

Note that when using the process dictionary for cryptographically secure random numbers one has to ensure that no code called between initializing the generator and between generating numbers accidentally alters the generator state in the process dictionary.

The safe approach is to use the rand functions that do not use the process dictionary but take an explicit state argument: the ones suffixed _s. Thereby it is rather rand_seed_s/0 that should be used instead of this function.

rand_seed_alg(Alg)

(since OTP 21.0)

-spec rand_seed_alg(Alg :: crypto) -> {rand:alg_handler(crypto), rand_plugin_state()};
                   (Alg :: crypto_cache) -> {rand:alg_handler(crypto_cache), rand_cache_state()};
                   (ExportState :: {crypto, rand_plugin_state()}) ->
                       {rand:alg_handler(crypto), rand_plugin_state()};
                   (ExportState :: {crypto_cache, rand_cache_state()}) ->
                       {rand:alg_handler(crypto_cache), rand_cache_state()};
                   (ExportState :: {crypto_aes, rand_plugin_aes_state()}) ->
                       {rand:alg_handler(crypto_aes), rand_plugin_aes_state()};
                   (ExportState :: {crypto_prng1, rand_plugin_prng1_init_state()}) ->
                       {rand:alg_handler(crypto_prng1), rand_plugin_prng1_init_state()};
                   (State) -> State
                       when
                           State ::
                               {rand:alg_handler(crypto), rand_plugin_state()} |
                               {rand:alg_handler(crypto_cache), rand_cache_state()} |
                               {rand:alg_handler(crypto_aes), rand_plugin_aes_state()} |
                               {rand:alg_handler(crypto_prng1), rand_plugin_prng1_state()}.

Create a generator for rand with specified algorithm, and save it in the process dictionary.

Equivalent to rand_seed_alg_s/1 but also saves the returned state object (generator) in the process dictionary. That is, equivalent to rand:seed(rand_seed_alg_s(Alg)).

See rand:seed/1 and rand_seed_alg_s/1. Note the warning about the usage of the process dictionary in rand_seed/0.

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)

(since OTP-22.0)

-spec rand_seed_alg(Alg :: crypto_aes, Seed :: iodata()) ->
                       {rand:alg_handler(crypto_aes), rand_plugin_aes_state()};
                   (Alg :: crypto_prng1, Seed :: iodata()) ->
                       {rand:alg_handler(crypto_prng1), rand_plugin_prng1_state()}.

Create and seed a generator for rand with specified algorithm, and save it in the process dictionary.

Equivalent to rand_seed_alg_s/2 but also saves the returned state object (generator) in the process dictionary. That is, equivalent to rand:seed(rand_seed_alg_s(Alg, Seed)).

See rand:seed/1 and rand_seed_alg_s/2. Note the warning about the usage of the process dictionary in rand_seed/0.

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/1

(since OTP 21.0)

-spec rand_seed_alg_s(Alg :: crypto) -> {rand:alg_handler(crypto), rand_plugin_state()};
                     (Alg :: crypto_cache) -> {rand:alg_handler(crypto_cache), rand_cache_state()};
                     (ExportState :: {crypto, rand_plugin_state()}) ->
                         {rand:alg_handler(crypto), rand_plugin_state()};
                     (ExportState :: {crypto_cache, rand_cache_state()}) ->
                         {rand:alg_handler(crypto_cache), rand_cache_state()};
                     (ExportState :: {crypto_aes, rand_plugin_aes_state()}) ->
                         {rand:alg_handler(crypto_aes), rand_plugin_aes_state()};
                     (ExportState :: {crypto_prng1, rand_plugin_prng1_init_state()}) ->
                         {rand:alg_handler(crypto_prng1), rand_plugin_prng1_init_state()};
                     (State) -> State
                         when
                             State ::
                                 {rand:alg_handler(crypto), rand_plugin_state()} |
                                 {rand:alg_handler(crypto_cache), rand_cache_state()} |
                                 {rand:alg_handler(crypto_aes), rand_plugin_aes_state()} |
                                 {rand:alg_handler(crypto_prng1), rand_plugin_prng1_state()}.

Create a generator for rand with specified algorithm.

Create a state object (generator) for random number generation, which when used by the rand functions produce cryptographically strong random number.

See rand:seed_s/1 and for example rand:uniform_s/2.

With Alg = crypto

The created generator uses OpenSSL's BN_rand_range for uniform integers and floats.

The generator also implements generating bytes efficiently with OpenSSL's RAND_bytes, just like strong_rand_bytes/1. See also rand:bytes_s/2. Since OTP 29.0.

Because the OpenSSL library is called for every request, this generator has got a very small generator state, but a large call overhead, so for numbers and small numbers of bytes (about 10), it becomes very slow compared to the default PRNG in the rand module. This is an unfair comparison because a PRNG is not cryptographically strong. Still, for a larger numbers of bytes, (about 1 000 or more) this generator is the fastest.

This function is equivalent to rand_seed_s/0.

With Alg = crypto_cache

The created generator fetches random data with OpenSSL's RAND_bytes, just like strong_rand_bytes/1, and caches it in the generator's state. Then 56 bit numbers are extracted from the cache, which makes operations in module rand fast on 64 bit machines.

The generator also implements extracting bytes efficiently. See also rand:bytes_s/2. Since OTP 29.0.

Caching random data improves amortized performance a lot so for numbers it becomes less than a factor 2 slower than the default PRNG in the rand module. For bytes it performs very much like for Alg = crypto above.

Since this generator caches random data it is a bad idea to copy its state in an attempt to fork into multiple generators. The forked generators will produce the same numbers until their caches are empty, which cannot be regarded as cryptographically strong, and is probably never useful.

Example

S0 = crypto:rand_seed_alg_s(crypto_cache),
{IntegerValue, S1} = rand:uniform(42, S0), % 1 .. 42
{FloatValue, S2} = rand:uniform(S1).       % [0.0, 1.0)

These generators may cause the rand functions using the returned state object to raise the exception error:low_entropy in case the random generator failed due to lack of secure "randomness".

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

Note

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

In fact when random data is cached some numbers may get reproduced, but this is unpredictable.

The only supported usage is to generate one distinct random sequence.

With argument ExportState

For completeness, this function accepts an ExportState from rand:export_seed_s/1 used on one of this module's generators. This function can probably only be useful for algorithm crypto_aes.

For algorithm crypto it is not very useful since the produced numbers are as unpredictable for a new generator as for one re-created with this function.

The same goes for algorithm crypto_cache, but its exported state may contain cached random numbers which might delay having to call OpenSSL the first time, so there is a possible slight performance gain.

For algorithm crypto_aes this function works as described in rand:export_seed_s/1 and rand:seed_s/1.

For algorithm crypto_prng1 this function only works as described in rand:export_seed_s/1 and rand:seed_s/1 on the initial state after creation (seeding). After the first random number has been created, the state contains a crypto_state/0 that does not survive a roundtrip through Erlang's external term format.

With argument State

For completeness, this function accepts a State just as rand:seed_s does. Calling this function with a State from one of the algorithms in this module only passes the state through, it is a no-op.

rand_seed_alg_s(Alg, Seed)

(since OTP 22.0)

-spec rand_seed_alg_s(Alg :: crypto_aes, Seed :: iodata()) ->
                         {rand:alg_handler(crypto_aes), rand_plugin_aes_state()};
                     (Alg :: crypto_prng1, Seed :: iodata()) ->
                         {rand:alg_handler(crypto_prng1), rand_plugin_prng1_state()}.

Create and seed a generator for rand with specified algorithm.

Create a state object (generator) for random number generation, which when used by the rand functions produce cryptographically unpredictable random numbers, that can be reproduced by re-using the same Seed.

See rand:seed_s/1, and for example rand:uniform_s/2, and compare to rand_seed_alg/1.

The state objects created by this function has cached data so they use much more memory than the generators in the rand module.

With Alg = crypto_aes

The Xoroshiro928 generator from the rand module is used as a counter. The generator's state is scrambled through AES-256 to create a 58-bit pseudo random value. This gives a long period (2^928 - 1).

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

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 with Alg =:= crypto_aes (or Alg =:= crypto_prng1, below).

If you do not need the statistical quality of these generators, there are faster generators in the rand module. The amortized speed of this generator is about 3 times slower than the rand module's default algorithm.

Example

1> S0 = crypto:rand_seed_alg_s(crypto_aes, "my seed").
2> %% 1..42
   {IntegerValue, S1} = rand:uniform_s(42, S0).
3> %% [0.0, 1.0)
   {FloatValue, S2} = rand:uniform_s(S1).
4> {IntegerValue,FloatValue}.
{9,0.7624867055217882}
5> S3 = crypto:rand_seed_alg_s(crypto_aes, "my seed").
6> %% Same values
   {IntegerValue, S4} = rand:uniform_s(42, S3).
7> %% again
   {FloatValue, S5} = rand:uniform_s(S4).

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 for speed reasons cached in the generator's state. The cache size can be changed from its default value using the crypto app's configuration parameter rand_cache_size.

Generating bytes, see rand:bytes_s/2, is done from the cached numbers, which limits the performance as for generating numbers. Alg = crypto, is faster, for larger numbers of bytes significantly faster, but cannot be used to reproduce a sequence. Another alternative is Alg = crypto_prng1 that follows here.

With Alg = crypto_prng1 Since OTP 29.0.

The created generator uses a stream cipher to encrypt data blocks of zeros, which effectively results in the stream cipher's key stream as binary data. The binary data is cached in the generator's state to achieve good amortized speed. From the cached data 58 bit numbers are extracted, to facilitate fast operations in the rand module. The cache size can be changed from its default value using the crypto app's configuration parameter rand_cache_size.

This generator also implements extracting bytes efficiently through rand:bytes_s/2.

The key stream from a stream cipher is cryptographically unpredictable, which should result in statistically completely unpredictable random values, but the generated numbers are not to be regarded as cryptographically strong since there is no re-keying schedule, and since the sequence is repeated for the same seed.

For generating numbers, this generator is about 2 times slower than the default PRNG in the rand module. For generating bytes, it is significantly faster, for any number of bytes. Compared to Alg = crypto, this generator has much less overhead, so for small numbers of bytes it is much faster. Break-even is a bit above the cache size, and over that Alg = crypto is faster, but cannot be used to reproduce a sequence.

Example

1> S0 = crypto:rand_seed_alg_s(crypto_prng1, "my seed").
2> %% 1..42
   {IntegerValue, S1} = rand:uniform_s(42, S0).
3> {Bytes, S2} = rand:bytes_s(7, S1).
4> {IntegerValue,Bytes}.
{20,<<52,185,212,38,248,228,127>>}
5> S3 = crypto:rand_seed_alg_s(crypto_prng1, "my seed").
6> %% Same values
   {IntegerValue, S4} = rand:uniform_s(42, S3).
7> %% again
   {Bytes, S5} = rand:bytes_s(7, S4).

The generator's state contains a crypto_state/0 which refers to the same encryption state even when copied, and the generator's state contains cached random data. It is therefore a bad idea to copy the state in an attempt to fork into multiple generators. The forked generators will produce the same numbers until their caches are empty, and then refill their caches with different sections of the keystream. This is probably never useful.

The created initial state, however, can be copied and exported, as descrided for rand:export_seed_s/1 and rand:seed_s/1, since the crypto_state/0 is not created until the first random value is generated. An exported subsequent generator state cannot be passed intact through Erlang's external term format, and rand_seed_alg_s/1 will fail for an exported state of this generator that is not an initial state.

rand:jump/1 is implemented for this generator, but also only for its initial state. A jump, for this generator, is implemented by incrementing the cipher's IV to create a distinct keystream. This is not much different from using different seed values, but avoids a call to the hash function that is used when seeding.

Example

1> Sa0 = crypto:rand_seed_alg_s(crypto_prng1, "my seed").
2> Sb0 = rand:jump(Sa0).
3> {BytesA, Sa1} = rand:bytes_s(7, Sa0).
4> {BytesB, Sb1} = rand:bytes_s(7, Sb0).
5> BytesA.
<<77,185,41,162,118,82,190>>
6> BytesB.
<<160,61,224,29,177,30,68>>
7> SA0 = crypto:rand_seed_alg_s(crypto_prng1, "my seed").
8> SB0 = rand:jump(SA0).
%% Same values again
9> {BytesA, SA1} = rand:bytes_s(7, SA0).
10> {BytesB, SB1} = rand:bytes_s(7, SB0).

Algorithm details

The Seed is hashed with SHA-384 to create a Key and IV for AES-256 that is run in CTR mode over blocks of zero data.

rand_seed_s()

(since OTP 20.0)

-spec rand_seed_s() -> {rand:alg_handler(crypto), rand_plugin_state()}.

Create a generator for rand.

Create a state object (generator) for random number generation, which when used by the rand functions produce cryptographically strong random numbers (based on OpenSSL's BN_rand_range function). See rand:seed_s/1, and for example rand:uniform_s/2.

This generator also implements generating bytes efficiently (based on OpenSSL's RAND_bytes function). See rand:bytes_s/2 and strong_rand_bytes/1. Since OTP 29.0.

Example

S0 = crypto:rand_seed_s(),
{RandomInteger, S1} = rand:uniform_s(1000, S0).

May cause the rand functions using this state object to raise the exception error:low_entropy in case the random generator failed due to lack of secure "randomness".

Note

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

The only supported usage is to generate one distinct random sequence.

Random API

rand_seed(Seed)

(since OTP 17.0)

-spec rand_seed(binary()) -> ok.

Mixes in the bytes of the given binary into the internal state of OpenSSL's random number generator.

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 or a generator from rand_seed_alg_s/1 raises error:low_entropy.

rand_uniform/2

This function is deprecated. crypto:rand_uniform/2 is deprecated; use strong_rand_range/1 instead.

-spec rand_uniform(crypto_integer(), crypto_integer()) -> crypto_integer().

Generate a random integer number.

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

Note

This function is deprecated because it originally used the OpenSSL method BN_pseudo_rand_range that was not cryptographically strong and could not run out of entropy. That behaviour changed in OpenSSL and this function cannot be fixed without making it raise error:low_entropy, which is not backwards compatible.

Instead, use strong_rand_range(To - From) + From

Be aware of the possible error:low_entropy exception.

strong_rand_bytes(N)

(since OTP R14B03)

-spec strong_rand_bytes(N :: non_neg_integer()) -> binary().

Generate bytes with randomly uniform values 0..255.

Returns the result in a binary with N bytes.

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

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

strong_rand_range/1

(since OTP 28.3)

-spec strong_rand_range(Range :: pos_integer()) -> N :: non_neg_integer();
                       (Range :: binary()) -> N :: binary().

Generate a random integer in a specified range.

The returned random integer is in the interval is 0 =< N < Range.

Uses the crypto library random number generator BN_rand_range.

If the Range argument is a pos_integer/0 the return value is a non_neg_integer/0. If the Range argument is a positive integer in a binary/0, the return value is a non-negative integer in a binary/0.

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

Sign/Verify API

sign(Algorithm, DigestType, Msg, Key)

(since OTP R16B01)

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

Equivalent to sign/5.

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

(since OTP 20.1)

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

Create a digital signature.

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

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

Uses the 3-tuple style for error handling.

See also public_key:sign/3.

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

(since OTP R16B01)

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

Equivalent to verify/6.

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

(since OTP 20.1)

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

Verify a digital signature.

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

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

Uses the 3-tuple style for error handling.

See also public_key:verify/4.

Utility Functions

bytes_to_integer(Bin)

(since OTP R16B01)

-spec bytes_to_integer(binary()) -> integer().

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

cipher_info(Type)

(since OTP 22.0)

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

Get information about a cipher algorithm.

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

Note

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

Always use a Type with an explicit key length,

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

ec_curve(CurveName)

(since OTP 17.0)

-spec ec_curve(CurveName) -> ExplicitCurve
                  when CurveName :: ec_named_curve(), ExplicitCurve :: ec_explicit_curve().

Return the defining parameters of a elliptic curve.

ec_curves()

(since OTP 17.0)

-spec ec_curves() -> [EllipticCurve]
                   when EllipticCurve :: ec_named_curve() | edwards_curve_dh() | edwards_curve_ed().

Return all supported named elliptic curves.

exor(Bin1, Bin2)

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

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

The two byte sequences must be of equal length.

hash_equals(BinA, BinB)

(since OTP 25.0)

-spec hash_equals(BinA, BinB) -> Result when BinA :: binary(), BinB :: binary(), Result :: boolean().

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

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

hash_info(Type)

(since OTP 22.0)

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

Get information about a hash algorithm.

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

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

info()

(since OTP 24.2)

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

Get information about crypto and the OpenSSL backend.

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

Example:

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

More association types than documented may be present in the map. Some of the associations (like fips) may be absent if not supported.

info_fips()

(since OTP 20.0)

-spec info_fips() -> not_supported | not_enabled | enabled.

Get information about the operating status of FIPS.

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

See configuration parameter fips_mode about how to enable FIPS mode.

Warning

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

info_lib()

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

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

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

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

Note

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

mod_pow(N, P, M)

(since OTP R16B01)

-spec mod_pow(N, P, M) -> Result
                 when
                     N :: binary() | integer(),
                     P :: binary() | integer(),
                     M :: binary() | integer(),
                     Result :: binary() | error.

Compute the function N^P mod M.

supports(Type)

(since OTP 22.0)

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

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

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