| 1 | package kdf |
| 2 | |
| 3 | import ( |
| 4 | "hash" |
| 5 | "math" |
| 6 | "github.com/dvsekhvalnov/jose2go/arrays" |
| 7 | ) |
| 8 | |
| 9 | const ( |
| 10 | MaxInt = int(^uint(0)>>1); |
| 11 | ) |
| 12 | |
| 13 | // DeriveConcatKDF implements NIST SP 800-56A Concatenation Key Derivation Function. Derives |
| 14 | // key material of keydatalen bits size given Z (sharedSecret), OtherInfo (AlgorithmID | |
| 15 | // PartyUInfo | PartyVInfo | SuppPubInfo | SuppPrivInfo) and hash function |
| 16 | func DeriveConcatKDF(keydatalen int, sharedSecret, algId, partyUInfo, partyVInfo, suppPubInfo, suppPrivInfo []byte, h hash.Hash) []byte { |
| 17 | |
| 18 | otherInfo := arrays.Concat(algId, partyUInfo, partyVInfo, suppPubInfo, suppPrivInfo) |
| 19 | |
| 20 | keyLenBytes := keydatalen >> 3 |
| 21 | |
| 22 | reps := int(math.Ceil(float64(keyLenBytes) / float64(h.Size()))) |
| 23 | |
| 24 | if reps > MaxInt { |
| 25 | panic("kdf.DeriveConcatKDF: too much iterations (more than 2^32-1).") |
| 26 | } |
| 27 | |
| 28 | dk:=make([]byte, 0, keyLenBytes) |
| 29 | |
| 30 | for counter := 1;counter <= reps;counter++ { |
| 31 | h.Reset() |
| 32 | |
| 33 | counterBytes:=arrays.UInt32ToBytes(uint32(counter)) |
| 34 | |
| 35 | h.Write(counterBytes) |
| 36 | h.Write(sharedSecret) |
| 37 | h.Write(otherInfo) |
| 38 | |
| 39 | dk = h.Sum(dk) |
| 40 | } |
| 41 | |
| 42 | return dk[:keyLenBytes] |
| 43 | } |