crypto

crypto

Crypto Functions

Description

This module provides a set of cryptographic functions.

• Hash functions - ` Secure Hash Standard`, ` The MD5 Message Digest Algorithm (RFC 1321)` and `The MD4 Message Digest Algorithm (RFC 1320)`

• Hmac functions - ` Keyed-Hashing for Message Authentication (RFC 2104) `

• Cmac functions - `The AES-CMAC Algorithm (RFC 4493)`

• Block ciphers - DES and AES in Block Cipher Modes - ` ECB, CBC, CFB, OFB, CTR and GCM `

• ` RSA encryption RFC 1321 `

• Digital signatures `Digital Signature Standard (DSS)` and` Elliptic Curve Digital Signature Algorithm (ECDSA) `

• ` Secure Remote Password Protocol (SRP - RFC 2945) `

• gcm: Dworkin, M., "Recommendation for Block Cipher Modes of Operation: Galois/Counter Mode (GCM) and GMAC", National Institute of Standards and Technology SP 800- 38D, November 2007.

Data types

`key_value() = integer() | binary() `

Always `binary()` when used as return value

`rsa_public() = [key_value()] = [E, N]  `

Where E is the public exponent and N is public modulus.

`rsa_private() = [key_value()] = [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,P2 are first and second prime factors. E1,E2 are first and second exponents. C is the CRT coefficient. Terminology is taken from ` RFC 3447`.

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

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

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

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

`srp_public() = key_value() `

Where is `A` or `B` from `SRP design`

`srp_private() = key_value() `

Where is `a` or `b` from `SRP design`

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

`dh_public() = key_value() `
`dh_private() = key_value() `
`dh_params() = [key_value()] = [P, G] | [P, G, PrivateKeyBitLength]`
`ecdh_public() = key_value() `
`ecdh_private() = key_value() `
`ecdh_params() = ec_named_curve() | ec_explicit_curve()`
```ec_explicit_curve() =
{ec_field(), Prime :: key_value(), Point :: key_value(), Order :: integer(),
CoFactor :: none | integer()} ```
```ec_field() = {prime_field, Prime :: integer()} |
{characteristic_two_field, M :: integer(), Basis :: ec_basis()}```
```ec_basis() = {tpbasis, K :: non_neg_integer()} |
{ppbasis, K1 :: non_neg_integer(), K2 :: non_neg_integer(), K3 :: non_neg_integer()} |
onbasis```
```ec_named_curve() ->
sect571r1| sect571k1| sect409r1| sect409k1| secp521r1| secp384r1| secp224r1| secp224k1|
secp192k1| secp160r2| secp128r2| secp128r1| sect233r1| sect233k1| sect193r2| sect193r1|
sect131r2| sect131r1| sect283r1| sect283k1| sect163r2| secp256k1| secp160k1| secp160r1|
secp112r2| secp112r1| sect113r2| sect113r1| sect239k1| sect163r1| sect163k1| secp256r1|
secp192r1|
brainpoolP160r1| brainpoolP160t1| brainpoolP192r1| brainpoolP192t1| brainpoolP224r1|
brainpoolP224t1| brainpoolP256r1| brainpoolP256t1| brainpoolP320r1| brainpoolP320t1|
brainpoolP384r1| brainpoolP384t1| brainpoolP512r1| brainpoolP512t1```

Note that the sect curves are GF2m (characteristic two) curves and are only supported if the underlying OpenSSL has support for them. See also `crypto:supports/0`

```engine_key_ref() = #{engine   := engine_ref(),
key_id   := key_id(),
`engine_ref() = term()`

The result of a call to `engine_load/3`.

`key_id() = string() | binary()`

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

`password() = string() | binary()`

`stream_cipher() = rc4 | aes_ctr `
```block_cipher() = aes_cbc | aes_cfb8 | aes_cfb128 | aes_ige256 | blowfish_cbc |
blowfish_cfb64 | des_cbc | des_cfb | des3_cbc | des3_cfb | des_ede3 | rc2_cbc ```
`aead_cipher() = aes_gcm | chacha20_poly1305 `
`stream_key() = aes_key() | rc4_key() `
`block_key() = aes_key() |  blowfish_key() | des_key()| des3_key() `
`aes_key() = iodata() `

Key length is 128, 192 or 256 bits

`rc4_key() = iodata() `

Variable key length from 8 bits up to 2048 bits (usually between 40 and 256)

`blowfish_key() = iodata() `

Variable key length from 32 bits up to 448 bits

`des_key() = iodata() `

Key length is 64 bits (in CBC mode only 8 bits are used)

`des3_key() = [binary(), binary(), binary()] `

Each key part is 64 bits (in CBC mode only 8 bits are used)

`digest_type() =  md5 | sha | sha224 | sha256 | sha384 | sha512`
`rsa_digest_type() = md5 | ripemd160 | sha | sha224 | sha256 | sha384 | sha512`
`dss_digest_type() = sha | sha224 | sha256 | sha384 | sha512`

Note that the actual supported dss_digest_type depends on the underlying crypto library. In OpenSSL version >= 1.0.1 the listed digest are supported, while in 1.0.0 only sha, sha224 and sha256 are supported. In version 0.9.8 only sha is supported.

`ecdsa_digest_type() = sha | sha224 | sha256 | sha384 | sha512`
`sign_options() = [{rsa_pad, rsa_sign_padding()} | {rsa_pss_saltlen, integer()}]`
`rsa_sign_padding() = rsa_pkcs1_padding | rsa_pkcs1_pss_padding`
`hash_algorithms() =  md5 | ripemd160 | sha | sha224 | sha256 | sha384 | sha512 `

md4 is also supported for hash_init/1 and hash/2. Note that both md4 and md5 are recommended only for compatibility with existing applications.

```cipher_algorithms() = aes_cbc | aes_cfb8 | aes_cfb128 | aes_ctr | aes_gcm |
aes_ige256 | blowfish_cbc | blowfish_cfb64 | chacha20_poly1305 | des_cbc |
des_cfb | des3_cbc | des3_cfb | des_ede3 | rc2_cbc | rc4 ```
`mac_algorithms() = hmac | cmac`
`public_key_algorithms() = rsa |dss | ecdsa | dh | ecdh | ec_gf2m`

Note that ec_gf2m is not strictly a public key algorithm, but a restriction on what curves are supported with ecdsa and ecdh.

```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```

Types

Encrypt `PlainText` according to `Type` block cipher.

May throw exception `notsup` in case the chosen `Type` is not supported by the underlying OpenSSL implementation.

Types

Decrypt `CipherText` according to `Type` block cipher.

May throw exception `notsup` in case the chosen `Type` is not supported by the underlying OpenSSL implementation.

Types

Encrypt `PlainText` according to `Type` block cipher. `IVec` is an arbitrary initializing vector.

In AEAD (Authenticated Encryption with Associated Data) mode, encrypt `PlainText`according to `Type` block cipher and calculate `CipherTag` that also authenticates the `AAD` (Associated Authenticated Data).

May throw exception `notsup` in case the chosen `Type` is not supported by the underlying OpenSSL implementation.

Types

Decrypt `CipherText` according to `Type` block cipher. `IVec` is an arbitrary initializing vector.

In AEAD (Authenticated Encryption with Associated Data) mode, decrypt `CipherText`according to `Type` block cipher and check the authenticity the `PlainText` and `AAD` (Associated Authenticated Data) using the `CipherTag`. May return `error` if the decryption or validation fail's

May throw exception `notsup` in case the chosen `Type` is not supported by the underlying OpenSSL implementation.

Types

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

Types

Computes the shared secret from the private key and the other party's public key. See also `public_key:compute_key/2`

Types

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

Types

Generates a public key of type `Type`. See also `public_key:generate_key/1`. May throw exception an exception of class `error`:

• `badarg`: an argument is of wrong type or has an illegal value,
• `low_entropy`: the random generator failed due to lack of secure "randomness",
• `computation_failed`: the computation fails of another reason than `low_entropy`.
Note

RSA key generation is only available if the runtime was built with dirty scheduler support. Otherwise, attempting to generate an RSA key will throw exception `error:notsup`.

Types

Computes a message digest of type `Type` from `Data`.

May throw exception `notsup` in case the chosen `Type` is not supported by the underlying OpenSSL implementation.

Types

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

May throw exception `notsup` in case the chosen `Type` is not supported by the underlying OpenSSL implementation.

Types

Updates the digest represented by `Context` using the given `Data`. `Context` must have been generated using `hash_init` or a previous call to this function. `Data` can be any length. `NewContext` must be passed into the next call to `hash_update` or `hash_final`.

Types

Finalizes the hash operation referenced by `Context` returned from a previous call to `hash_update`. The size of `Digest` is determined by the type of hash function used to generate it.

Types

Computes a HMAC of type `Type` from `Data` using `Key` as the authentication key.

`MacLength` will limit the size of the resultant `Mac`.

Types

Initializes the context for streaming HMAC operations. `Type` determines which hash function to use in the HMAC operation. `Key` is the authentication key. The key can be any length.

Types

Updates the HMAC represented by `Context` using the given `Data`. `Context` must have been generated using an HMAC init function (such as `hmac_init`). `Data` can be any length. `NewContext` must be passed into the next call to `hmac_update` or to one of the functions `hmac_final` and `hmac_final_n`

Warning

Do not use a `Context` as argument in more than one call to hmac_update or hmac_final. The semantics of reusing old contexts in any way is undefined and could even crash the VM in earlier releases. The reason for this limitation is a lack of support in the underlying OpenSSL API.

Types

Finalizes the HMAC operation referenced by `Context`. The size of the resultant MAC is determined by the type of hash function used to generate it.

Types

Finalizes the HMAC operation referenced by `Context`. `HashLen` must be greater than zero. `Mac` will be a binary with at most `HashLen` bytes. Note that if HashLen is greater than the actual number of bytes returned from the underlying hash, the returned hash will have fewer than `HashLen` bytes.

Types

Computes a CMAC of type `Type` from `Data` using `Key` as the authentication key.

`MacLength` will limit the size of the resultant `Mac`.

Types

Provides information about the FIPS operating status of crypto and the underlying OpenSSL 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`.

Warning

In FIPS mode all non-FIPS compliant algorithms are disabled and throw exception `not_supported`. Check `supports` that in FIPS mode returns the restricted list of available algorithms.

Types

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

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

```> info_lib().
[{<<"OpenSSL">>,269484095,<<"OpenSSL 1.1.0c  10 Nov 2016"">>}]
```
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 OpenSSL library used at runtime. In earlier OTP versions both numeric and text was taken from the library.

Types

Computes the function `N^P mod M`.

Types

Returns the initialization vector to be used in the next iteration of encrypt/decrypt of type `Type`. `Data` is the encrypted data from the previous iteration step. The `IVec` argument is only needed for `des_cfb` as the vector used in the previous iteration step.

Types

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

Types

Fetches the corresponding public key from a private key stored in an Engine. The key must be of the type indicated by the Type parameter.

Types

The size of the `PlainText` must be less than `byte_size(N)-11` if `rsa_pkcs1_padding` is used, and `byte_size(N)` if `rsa_no_padding` is used, where N is public modulus of the RSA 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]`

Types

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

Types

The size of the `PlainText` must be less than `byte_size(N)-11` if `rsa_pkcs1_padding` is used, and `byte_size(N)` if `rsa_no_padding` is used, where N is public modulus of the RSA 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]`

Types

Set the seed for PRNG to the given binary. This calls the RAND_seed function from openssl. Only use this if the system you are running on does not have enough "randomness" built in. Normally this is when `strong_rand_bytes/1` throws `low_entropy`

Types

Generate a random number `N, Lo =< N < Hi.` Uses the `crypto` library pseudo-random number generator. `Hi` must be larger than `Lo`.

Types

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

Creates a digital signature.

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

See also `public_key:sign/3`.

`start() -> ok`

Equivalent to application:start(crypto).

`stop() -> ok`

Equivalent to application:stop(crypto).

Types

Generates N bytes randomly uniform 0..255, and returns the result in a binary. Uses a cryptographically secure prng seeded and periodically mixed with operating system provided entropy. By default this is the `RAND_bytes` method from OpenSSL.

May throw exception `low_entropy` in case the random generator failed due to lack of secure "randomness".

`rand_seed() -> rand:state()`

Creates state object for `random number generation`, in order to generate cryptographically strong random numbers (based on OpenSSL's `BN_rand_range`), and saves it on process dictionary before returning it as well. See also `rand:seed/1`.

Example

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

`rand_seed_s() -> rand:state()`

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

Types

Initializes the state for use in RC4 stream encryption `stream_encrypt` and `stream_decrypt`

Types

Initializes the state for use in streaming AES encryption using Counter mode (CTR). `Key` is the AES key and must be either 128, 192, or 256 bits long. `IVec` is an arbitrary initializing vector of 128 bits (16 bytes). This state is for use with `stream_encrypt` and `stream_decrypt`.

Types

Encrypts `PlainText` according to the stream cipher `Type` specified in stream_init/3. `Text` can be any number of bytes. The initial `State` is created using `stream_init`. `NewState` must be passed into the next call to `stream_encrypt`.

Types

Decrypts `CipherText` according to the stream cipher `Type` specified in stream_init/3. `PlainText` can be any number of bytes. The initial `State` is created using `stream_init`. `NewState` must be passed into the next call to `stream_decrypt`.

Types

Can be used to determine which crypto algorithms that are supported by the underlying OpenSSL library

Types

Can be used to determine which named elliptic curves are supported.

Types

Return the defining parameters of a elliptic curve.

Types

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

Verifies a digital signature

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

See also `public_key:verify/4`.

Types

Returns a list of all possible engine methods.

May throw exception notsup in case there is no engine support in the underlying OpenSSL implementation.

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

Types

Loads the OpenSSL engine given by `EngineId` if it is available and then returns ok and an engine handle. This function is the same as calling `engine_load/4` with `EngineMethods` set to a list of all the possible methods. An error tuple is returned if the engine can't be loaded.

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

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

Types

Loads the OpenSSL engine given by `EngineId` if it is available and then returns ok and an engine handle. An error tuple is returned if the engine can't be loaded.

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

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

Types

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

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

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

Types

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

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

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

Types

Sends ctrl commands to the OpenSSL engine given by `Engine`. This function is the same as calling `engine_ctrl_cmd_string/4` with `Optional` set to `false`.

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

Types

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

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