Skip to content

Commit fdf28bb

Browse files
authored
crypto.hmac: optimize hmac.new, support calculations with a blocksize > 256 (#25686)
1 parent 393d5b9 commit fdf28bb

File tree

1 file changed

+8
-14
lines changed

1 file changed

+8
-14
lines changed

vlib/crypto/hmac/hmac.v

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,32 +4,26 @@ module hmac
44

55
import crypto.internal.subtle
66

7-
const ipad = []u8{len: 256, init: 0x36} // TODO: is 256 enough??
8-
9-
const opad = []u8{len: 256, init: 0x5C}
10-
const npad = []u8{len: 256, init: 0}
11-
127
// new returns a HMAC byte array, depending on the hash algorithm used.
138
pub fn new(key []u8, data []u8, hash_func fn ([]u8) []u8, blocksize int) []u8 {
9+
mut inner := []u8{len: blocksize, init: 0x36}
10+
mut outer := []u8{len: blocksize, init: 0x5C}
11+
1412
mut b_key := []u8{}
1513
if key.len <= blocksize {
1614
b_key = key.clone() // TODO: remove .clone() once https://github.com/vlang/v/issues/6604 gets fixed
1715
} else {
1816
b_key = hash_func(key)
1917
}
20-
if b_key.len < blocksize {
21-
b_key << npad[..blocksize - b_key.len]
18+
if b_key.len > blocksize {
19+
b_key = b_key[..blocksize].clone()
2220
}
23-
mut inner := []u8{}
24-
for i, b in ipad[..blocksize] {
25-
inner << b_key[i] ^ b
21+
for i, b in b_key {
22+
inner[i] = b ^ 0x36
23+
outer[i] = b ^ 0x5c
2624
}
2725
inner << data
2826
inner_hash := hash_func(inner)
29-
mut outer := []u8{cap: b_key.len}
30-
for i, b in opad[..blocksize] {
31-
outer << b_key[i] ^ b
32-
}
3327
outer << inner_hash
3428
digest := hash_func(outer)
3529
return digest

0 commit comments

Comments
 (0)