package kdf

  1. Overview
  2. Docs
Key Derivation Functions: HKDF RFC 5869, PBKDF RFC 2898, SCRYPT RFC 7914

Install

dune-project
 Dependency

Authors

Maintainers

Sources

kdf-1.1.1.tbz
sha256=922efdf80d35b8fcb0ec7d0143400f45bb986cb1c715d717d5402f111cf8f8e5
sha512=8584c24b249d9d264fc58e1cd8299968b6098fe915fe7c8f935937c7e3cb200bde0bd0fdb042fb000337fb0b6298866068933cd20b95e51a021cbf3e9e3c6456

doc/src/kdf.hkdf/hkdf.ml.html

Source file hkdf.ml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

module type S = sig
  val extract : ?salt:string -> string -> string
  val expand : prk:string -> ?info:string -> int -> string
end

module Make (H : Digestif.S) : S = struct
  let extract ?salt ikm =
    let key = match salt with
      | None -> String.make H.digest_size '\x00'
      | Some x -> x
    in
    H.(to_raw_string (hmac_string ~key ikm))

  let expand ~prk ?info len =
    if len < 0 then
      failwith "len must be non-negative"
    else if len > 255 * H.digest_size then
      failwith "len must be at most 255 * digest_size";
    let info = match info with
      | None -> ""
      | Some x -> x
    in
    let t n last =
      let nc = String.make 1 (Char.unsafe_chr n) in
      H.(to_raw_string (hmac_string ~key:prk (String.concat "" [last ; info ; nc])))
    in
    let n = (len + H.digest_size - 1) / H.digest_size in
    let rec compute acc count = match count, acc with
      | c, xs when c > n -> String.concat "" (List.rev xs)
      | c, x::_ -> compute (t c x :: acc) (succ c)
      | _, [] -> invalid_arg "can not happen"
    in
    let buf = compute [""] 1 in
    String.sub buf 0 len
end

let extract ~hash ?salt ikm =
  let module H = (val (Digestif.module_of_hash' hash)) in
  let module HKDF = Make (H) in
  HKDF.extract ?salt ikm

let expand ~hash ~prk ?info len =
  let module H = (val (Digestif.module_of_hash' hash)) in
  let module HKDF = Make (H) in
  HKDF.expand ~prk ?info len