| 1 |
// package kdf contains implementations of various key derivation functions |
| 2 |
package kdf |
| 3 |
|
| 4 |
import ( |
| 5 |
"crypto/hmac" |
| 6 |
"fmt" |
| 7 |
"hash" |
| 8 |
"math" |
| 9 |
|
| 10 |
"github.com/dvsekhvalnov/jose2go/arrays" |
| 11 |
) |
| 12 |
|
| 13 |
// DerivePBKDF2 implements Password Based Key Derivation Function 2, RFC 2898. Derives key of keyBitLength size, given password, salt, iteration count and hash function |
| 14 |
func DerivePBKDF2(password, salt []byte, iterationCount, keyBitLength int, h func() hash.Hash) []byte { |
| 15 |
|
| 16 |
prf := hmac.New(h, password) |
| 17 |
hLen := prf.Size() |
| 18 |
dkLen := keyBitLength >> 3 //size of derived key in bytes |
| 19 |
|
| 20 |
l := int(math.Ceil(float64(dkLen) / float64(hLen))) // l = CEIL (dkLen / hLen) |
| 21 |
r := dkLen - (l-1)*hLen |
| 22 |
|
| 23 |
// 1. If dkLen > (2^32 - 1) * hLen, output "derived key too long" and stop. |
| 24 |
if dkLen > MaxInt { |
| 25 |
panic(fmt.Sprintf("kdf.DerivePBKDF2: expects derived key size to be not more that (2^32-1) bits, but was requested %v bits.", keyBitLength)) |
| 26 |
} |
| 27 |
|
| 28 |
dk := make([]byte, 0, dkLen) |
| 29 |
|
| 30 |
for i := 0; i < l; i++ { |
| 31 |
|
| 32 |
t := f(salt, iterationCount, i+1, prf) // T_l = F (P, S, c, l) |
| 33 |
|
| 34 |
if i == (l - 1) { |
| 35 |
t = t[:r] |
| 36 |
} // truncate last block to r bits |
| 37 |
|
| 38 |
dk = append(dk, t...) // DK = T_1 || T_2 || ... || T_l<0..r-1> |
| 39 |
} |
| 40 |
|
| 41 |
return dk |
| 42 |
} |
| 43 |
|
| 44 |
func f(salt []byte, iterationCount, blockIndex int, prf hash.Hash) []byte { |
| 45 |
|
| 46 |
prf.Reset() |
| 47 |
prf.Write(salt) |
| 48 |
prf.Write(arrays.UInt32ToBytes(uint32(blockIndex))) |
| 49 |
|
| 50 |
u := prf.Sum(nil) // U_1 = PRF (P, S || INT (i)) |
| 51 |
|
| 52 |
result := u |
| 53 |
|
| 54 |
for i := 2; i <= iterationCount; i++ { |
| 55 |
prf.Reset() |
| 56 |
prf.Write(u) |
| 57 |
|
| 58 |
u = prf.Sum(nil) // U_c = PRF (P, U_{c-1}) . |
| 59 |
result = arrays.Xor(result, u) // U_1 \xor U_2 \xor ... \xor U_c |
| 60 |
} |
| 61 |
|
| 62 |
return result |
| 63 |
} |