19992013 Ericsson AB. All Rights Reserved. The contents of this file are subject to the Erlang Public License, Version 1.1, (the "License"); you may not use this file except in compliance with the License. You should have received a copy of the Erlang Public License along with this software. If not, it can be retrieved online at http://www.erlang.org/. Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. crypto
crypto Crypto Functions

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)

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

RSA encryption RFC 1321

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

Secure Remote Password Protocol (SRP - RFC 2945)

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]

ecdh_public() = key_value()

ecdh_private() = key_value()

ecdh_params() = ec_named_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

stream_cipher() = rc4 | aes_ctr

block_cipher() = aes_cbc128 | aes_cfb128 | blowfish_cbc | blowfish_cfb64 | des_cbc | des_cfb | des3_cbc | des3_cbf | des_ede3 | rc2_cbc

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

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() = des_cbc | des_cfb | des3_cbc | des3_cbf | des_ede3 | blowfish_cbc | blowfish_cfb64 | aes_cbc128 | aes_cfb128| aes_cbc256 | rc2_cbc | aes_ctr| rc4

public_key_algorithms() = rsa |dss | ecdsa | dh | ecdh

block_encrypt(Type, Key, Ivec, PlainText) -> CipherText Encrypt PlainTextaccording to Type block cipher Type = block_cipher() Key = block_key() PlainText = iodata() IVec = CipherText = binary()

Encrypt PlainTextaccording to Type block cipher. IVec is an arbitrary initializing vector.

block_decrypt(Type, Key, Ivec, CipherText) -> PlainText Decrypt CipherTextaccording to Type block cipher Type = block_cipher() Key = block_key() PlainText = iodata() IVec = CipherText = binary()

Decrypt CipherTextaccording to Type block cipher. IVec is an arbitrary initializing vector.

bytes_to_integer(Bin) -> Integer Convert binary representation, of an integer, to an Erlang integer. Bin = binary() - as returned by crypto functions Integer = integer()

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

compute_key(Type, OthersPublicKey, MyKey, Params) -> SharedSecret Computes the shared secret Type = dh | ecdh | srp OthersPublicKey = dh_public() | ecdh_public() | srp_public() MyKey = dh_private() | ecdh_private() | {srp_public(),srp_private()} Params = dh_params() | ecdh_params() | SrpUserParams | SrpHostParams SrpUserParams = {user, [DerivedKey::binary(), Prime::binary(), Generator::binary(), Version::atom() | [Scrambler:binary()]]} SrpHostParams = {host, [Verifier::binary(), Prime::binary(), Version::atom() | [Scrambler::binary]]} SharedSecret = binary()

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

exor(Data1, Data2) -> Result XOR data Data1, Data2 = iodata() Result = binary()

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

generate_key(Type, Params) -> {PublicKey, PrivKeyOut} generate_key(Type, Params, PrivKeyIn) -> {PublicKey, PrivKeyOut} Generates a public keys of type Type Type = dh | ecdh | srp Params = dh_params() | ecdh_params() | SrpUserParams | SrpHostParams SrpUserParams = {user, [Generator::binary(), Prime::binary(), Version::atom()]} SrpHostParams = {host, [Verifier::binary(), Generator::binary(), Prime::binary(), Version::atom()]} PublicKey = dh_public() | ecdh_public() | srp_public() PrivKeyIn = undefined | dh_private() | srp_private() PrivKeyOut = dh_private() | ecdh_private() | srp_private()

Generates public keys of type Type. See also public_key:generate_key/1

hash(Type, Data) -> Digest Type = md4 | message_digest_algorithms() Data = iodata() Digest = binary()

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.

hash_init(Type) -> Context Type = md4 | message_digest_algorithms()

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.

hash_update(Context, Data) -> NewContext Data = iodata()

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

hash_final(Context) -> Digest Digest = binary()

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.

hmac(Type, Key, Data) -> Mac hmac(Type, Key, Data, MacLength) -> Mac Type = message_digest_algorithms() Key = iodata() Data = iodata() MacLength = integer() Mac = binary()

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

MacLength will limit the size of the resultant Mac.
hmac_init(Type, Key) -> Context Type = message_digest_algorithms() Key = iodata() Context = binary()

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

hmac_update(Context, Data) -> NewContext Context = NewContext = binary() Data = iodata()

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

hmac_final(Context) -> Mac Context = Mac = binary()

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

hmac_final_n(Context, HashLen) -> Mac Context = Mac = binary() HashLen = non_neg_integer()

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.

info_lib() -> [{Name,VerNum,VerStr}] Provides information about the libraries used by crypto. Name = binary() VerNum = integer() VerStr = binary()

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">>,9469983,<<"OpenSSL 0.9.8a 11 Oct 2005">>}]
        

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.

mod_pow(N, P, M) -> Result Computes the function: N^P mod M N, P, M = binary() | integer() Result = binary() | error

Computes the function N^P mod M.

next_iv(Type, Data) -> NextIVec next_iv(Type, Data, IVec) -> NextIVec Type = des_cbc | des3_cbc | aes_cbc | des_cfb Data = iodata() IVec = NextIVec = binary()

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

private_decrypt(Type, ChipherText, PrivateKey, Padding) -> PlainText Decrypts ChipherText using the private Key. Type = rsa ChipherText = binary() PrivateKey = rsa_private() Padding = rsa_pkcs1_padding | rsa_pkcs1_oaep_padding | rsa_no_padding PlainText = binary()

Decrypts the ChipherText (usually a session key encrypted with public_encrypt/3) using the PrivateKey and returns the message. The Padding is the padding mode that was used to encrypt the data, see public_encrypt/3. See also public_key:decrypt_private/[2,3]

private_encrypt(Type, PlainText, PrivateKey, Padding) -> ChipherText Encrypts Msg using the private Key. Type = rsa PlainText = binary() PrivateKey = rsa_private() Padding = rsa_pkcs1_padding | rsa_no_padding ChipherText = binary()

Encrypts the PlainText using the PrivateKey and returns the cipher. The Padding decides what padding mode is used, rsa_pkcs1_padding is PKCS #1 v1.5 currently the most used mode. The size of the Msg must be less than byte_size(N)-11 if rsa_pkcs1_padding is used, and byte_size(N) if rsa_no_padding is used. See also public_key:encrypt_private/[2,3]

public_decrypt(Type, ChipherText, PublicKey, Padding) -> PlainText Decrypts ChipherText using the public Key. Type = rsa ChipherText = binary() PublicKey = rsa_public() Padding = rsa_pkcs1_padding | rsa_no_padding PlainText = binary()

Decrypts the ChipherText (encrypted with private_encrypt/3) using the PrivateKey and returns the message. The Padding is the padding mode that was used to encrypt the data, see private_encrypt/3. See also public_key:decrypt_public/[2,3]

public_encrypt(Type, PlainText, PublicKey, Padding) -> ChipherText Encrypts Msg using the public Key. Type = rsa PlainText = binary() PublicKey = rsa_public() Padding = rsa_pkcs1_padding | rsa_pkcs1_oaep_padding | rsa_no_padding ChipherText = binary()

Encrypts the PlainText (usually a session key) using the PublicKey and returns the CipherText. The Padding decides what padding mode is used, rsa_pkcs1_padding is PKCS #1 v1.5 currently the most used mode and rsa_pkcs1_oaep_padding is EME-OAEP as defined in PKCS #1 v2.0 with SHA-1, MGF1 and an empty encoding parameter. This mode is recommended for all new applications. The size of the Msg must be less than byte_size(N)-11 if rsa_pkcs1_padding is used, byte_size(N)-41 if rsa_pkcs1_oaep_padding is used and byte_size(N) if rsa_no_padding is used. See also public_key:encrypt_public/[2,3]

rand_bytes(N) -> binary() Generate a binary of random bytes N = integer()

Generates N bytes randomly uniform 0..255, and returns the result in a binary. Uses the crypto library pseudo-random number generator.

rand_uniform(Lo, Hi) -> N Generate a random number Lo, Hi, N = integer()

Generate a random number Uses the crypto library pseudo-random number generator. Hi must be larger than Lo.

sign(Algorithm, DigestType, Msg, Key) -> binary() Create digital signature. Algorithm = rsa | dss | ecdsa Msg = binary() | {digest,binary()} The msg is either the binary "plain text" data to be signed or it is the hashed value of "plain text" i.e. the digest. DigestType = digest_type() Key = rsa_private() | dss_private() | [ecdh_private(),ecdh_params()]

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

Equivalent to application:start(crypto).

stop() -> ok Equivalent to application:stop(crypto).

Equivalent to application:stop(crypto).

strong_rand_bytes(N) -> binary() Generate a binary of random bytes N = integer()

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

stream_init(Type, Key) -> State Type = rc4 State = opaque() Key = iodata()

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

stream_init(Type, Key, IVec) -> State Type = aes_ctr State = opaque() Key = iodata() IVec = binary()

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 bts long. IVec is an arbitrary initializing vector of 128 bits (16 bytes). This state is for use with stream_encrypt and stream_decrypt.

stream_encrypt(State, PlainText) -> { NewState, CipherText} Text = iodata() CipherText = binary()

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

stream_decrypt(State, CipherText) -> { NewState, PlainText } CipherText = iodata() PlainText = binary()

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

supports() -> AlgorithmList Provide a list of available crypto algorithms. AlgorithmList = [{hashs, [hash_algorithms()]}, {ciphers, [cipher_algorithms()]}, {public_keys, [public_key_algorithms()]}

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

verify(Algorithm, DigestType, Msg, Signature, Key) -> boolean() Verifies a digital signature. Algorithm = rsa | dss | ecdsa Msg = binary() | {digest,binary()} The msg is either the binary "plain text" data or it is the hashed value of "plain text" i.e. the digest. DigestType = digest_type() Signature = binary() Key = rsa_public() | dss_public() | [ecdh_public(),ecdh_params()]

Verifies a digital signature

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

See also public_key:verify/3