hkdf.go raw
1 package hkdf
2
3 import "common/crypto/hmac"
4
5 // Extract computes HKDF-Extract: PRK = HMAC-SHA256(salt, ikm).
6 func Extract(salt, ikm []byte) [32]byte {
7 if len(salt) == 0 {
8 salt = make([]byte, 32)
9 }
10 return hmac.Sum(salt, ikm)
11 }
12
13 // Expand computes HKDF-Expand using HMAC-SHA256.
14 // Returns length bytes of output keying material.
15 func Expand(prk, info []byte, length int) []byte {
16 out := make([]byte, 0, length)
17 var prev []byte
18 counter := byte(1)
19 for len(out) < length {
20 // T(i) = HMAC(PRK, T(i-1) || info || counter)
21 input := make([]byte, len(prev)+len(info)+1)
22 copy(input, prev)
23 copy(input[len(prev):], info)
24 input[len(input)-1] = counter
25 t := hmac.Sum(prk[:], input)
26 prev = t[:]
27 out = append(out, t[:]...)
28 counter++
29 }
30 return out[:length]
31 }
32