-
Notifications
You must be signed in to change notification settings - Fork 21
/
kdftree.go
51 lines (39 loc) · 1.22 KB
/
kdftree.go
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
47
48
49
50
51
package kdftree
import (
"hash"
"crypto/hmac"
"encoding/binary"
"github.com/deatil/go-cryptobin/hash/gost/gost34112012256"
)
// KDFTree implements KDF_TREE_GOSTR3411_2012_256 algorithm for r = 1.
// https://tools.ietf.org/html/rfc7836#section-4.5
func KDFTree(secret []byte, label, seed []byte, length int) []byte {
return Key(gost34112012256.New, secret, label, seed, length)
}
// Key implements KDF_TREE_GOSTR3411_2012_256 algorithm for r = 1.
// https://tools.ietf.org/html/rfc7836#section-4.5
func Key(h func() hash.Hash, secret []byte, label, seed []byte, length int) []byte {
mdSize := h().Size()
if length == 0 ||
length%mdSize != 0 ||
length > mdSize*(1<<8-1) {
panic("KDFtree wrong length parameter")
}
out := make([]byte, 0, length)
L := uint16(8 * length)
Lb := make([]byte, 2)
binary.BigEndian.PutUint16(Lb, L)
// The number of iterations, n <= 255
n := uint8(length / mdSize)
mac := hmac.New(h, secret)
for i := uint8(1); i <= n; i++ {
mac.Reset()
mac.Write([]byte{i})
mac.Write(label)
mac.Write([]byte{0x00})
mac.Write(seed)
mac.Write(Lb)
out = mac.Sum(out)
}
return out
}