Module Webs_kit.Sha_256

SHA-256 hashes, HMAC-SHA-256 and PBKDF2-HMAC-SHA-256.

Hash values

type t

The type for SHA-256 hashes.

val length : t -> int

length h is the length of h in bytes (i.e. 32).

val hash : string -> t

hash s is the SHA-256 hash of s.

HMAC-SHA-256

val hmac : key:string -> string -> t

hmac ~key msg is the RFC 2104 HMAC-SHA-256 for key key and message msg. key should not be less than 32 bytes.

PBKDF2-HMAC-SHA-256

val pbkdf2_hmac : key_len:int -> iterations:int -> pass:string -> salt:string -> unit -> string

pbkdf2_hmac ~key_len ~iterations ~pass ~salt () derives a key for password pass with a salt salt and iterations iterations iterations (use at least 100_000) wto generate a key of length key_len using RFC 8018's PBKFD2-HMAC-SHA-256.

In 2021, here is a good baseline of parameters:

  • A key_len of 32 bytes.
  • A number of iterations of 400_000.
  • A salt length of 8 bytes.

Raises Invalid_argument if key_len or iterations are smaller or equal to 0 or if key_len is greater than 232 - 1 * 32 or max_int.

Predicates and comparisons

val equal : t -> t -> bool

equal h0 h1 is true iff h0 and h1 are equal.

val compare : t -> t -> int

compare h0 h1 is a total order on hashes compatible with equal.

Converting

val to_bytes : t -> string

to_bytes h is the sequence of bytes of h.

val of_bytes : string -> (t, unit) Stdlib.result

of_bytes s is the sequence of bytes of s as a hash value. An error is returned if the length of s in not 32.

val to_hex : t -> string

to_ascii_hex h is the sequence of bytes of h as US-ASCII lowercase hexadecimal digits.

val of_hex : string -> (t, int) Stdlib.result

of_hex s parses a sequence of US-ASCII (lower or upper cased) hexadecimal digits to its hash value. Errors with an offending index or the length of the string in case s was not exactly made of 64 US-ASCII hex digits.

val pp : Stdlib.Format.formatter -> t -> unit

pp formats digests with to_hex.