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.


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.


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.

Warning. Use equal_key to compare derived keys, not String.equal or ( = ).

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.

Warning. Use equal_key to compare derived keys, not String.equal or ( = ).

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.

val equal_key : string -> string -> bool

equal_key k0 k1 is a constant time string equality for k0 and k1 of the same length. Do not use to compare string of different lengths this raises Invalid_argument in that case.

Predicates and comparisons

val equal : t -> t -> bool

equal h0 h1 is a constant time equality comparison function between h0 and h1.


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.