SequenceHash.Algorithm (SequenceHash v0.1.0)

Copy Markdown View Source

The underlying hash functions this library accepts.

The specification allows SequenceHash and SequenceMAC to be built on almost any hash function, and lets implementations reject hash functions that are insecure or have short outputs, provided the rejection is documented (spec section "Hash function support").

This library accepts exactly the hash functions covered by the C2SP/CCTV test vectors whose output is at least 32 bytes:

AlgorithmBlock size b (bytes)Output length L (bytes)
:sha2566432
:sha51212864
:sha3_25613632
:sha3_5127264
:blake2b12864
:blake2s6432

The sizes are copied from the specification's "Block size guidance" table. For SHA-3 the block size is the sponge rate. :blake2b and :blake2s are the OTP :crypto names for BLAKE2b-512 and BLAKE2s-256.

Everything else is rejected with an ArgumentError. That includes SHA-1 (:sha), MD5, and any hash whose output is shorter than 32 bytes, so the specification's warnings about "short hashes" never apply.

Summary

Types

t()

A supported underlying hash function, named as in :crypto.

Functions

Returns the block size b of algorithm, in bytes.

Guard that is true when algorithm is a supported hash function.

Returns the output length L of algorithm, in bytes.

Lists the supported hash functions.

Returns algorithm unchanged if it is supported, otherwise raises.

Types

t()

@type t() :: :sha256 | :sha512 | :sha3_256 | :sha3_512 | :blake2b | :blake2s

A supported underlying hash function, named as in :crypto.

Functions

block_size(algorithm)

@spec block_size(t()) :: pos_integer()

Returns the block size b of algorithm, in bytes.

iex> SequenceHash.Algorithm.block_size(:sha3_256)
136

is_supported(algorithm)

(macro)

Guard that is true when algorithm is a supported hash function.

output_size(algorithm)

@spec output_size(t()) :: pos_integer()

Returns the output length L of algorithm, in bytes.

iex> SequenceHash.Algorithm.output_size(:blake2b)
64

supported()

@spec supported() :: [t()]

Lists the supported hash functions.

iex> SequenceHash.Algorithm.supported()
[:blake2b, :blake2s, :sha256, :sha3_256, :sha3_512, :sha512]

validate!(algorithm)

@spec validate!(term()) :: t()

Returns algorithm unchanged if it is supported, otherwise raises.

iex> SequenceHash.Algorithm.validate!(:sha256)
:sha256

iex> SequenceHash.Algorithm.validate!(:sha)
** (ArgumentError) unsupported hash algorithm :sha; supported algorithms are [:blake2b, :blake2s, :sha256, :sha3_256, :sha3_512, :sha512]

Values that are not atoms are not echoed in the message, because a common mistake is to swap the algorithm and key arguments:

iex> SequenceHash.Algorithm.validate!("a secret key")
** (ArgumentError) hash algorithm must be an atom, got a binary; supported algorithms are [:blake2b, :blake2s, :sha256, :sha3_256, :sha3_512, :sha512]