2020-10-14 12:25:58 +02:00
|
|
|
// HMAC: Keyed-Hashing for Message Authentication implemented in v
|
|
|
|
// implementation based on https://tools.ietf.org/html/rfc2104
|
|
|
|
module hmac
|
|
|
|
|
2020-10-14 16:21:43 +02:00
|
|
|
import crypto.internal.subtle
|
|
|
|
|
2020-10-14 12:25:58 +02:00
|
|
|
const (
|
2022-04-15 14:35:35 +02:00
|
|
|
ipad = []u8{len: 256, init: 0x36} // TODO is 256 enough??
|
|
|
|
opad = []u8{len: 256, init: 0x5C}
|
|
|
|
npad = []u8{len: 256, init: 0}
|
2020-10-14 12:25:58 +02:00
|
|
|
)
|
|
|
|
|
2021-01-23 13:33:49 +01:00
|
|
|
// new returns a HMAC byte array, depending on the hash algorithm used.
|
2022-04-15 14:35:35 +02:00
|
|
|
pub fn new(key []u8, data []u8, hash_func fn ([]u8) []u8, blocksize int) []u8 {
|
|
|
|
mut b_key := []u8{}
|
2020-10-14 12:25:58 +02:00
|
|
|
if key.len <= blocksize {
|
|
|
|
b_key = key.clone() // TODO: remove .clone() once https://github.com/vlang/v/issues/6604 gets fixed
|
|
|
|
} else {
|
|
|
|
b_key = hash_func(key)
|
|
|
|
}
|
|
|
|
if b_key.len < blocksize {
|
2021-05-08 12:32:29 +02:00
|
|
|
b_key << hmac.npad[..blocksize - b_key.len]
|
2020-10-14 12:25:58 +02:00
|
|
|
}
|
2022-04-15 14:35:35 +02:00
|
|
|
mut inner := []u8{}
|
2021-05-08 12:32:29 +02:00
|
|
|
for i, b in hmac.ipad[..blocksize] {
|
2020-10-14 12:25:58 +02:00
|
|
|
inner << b_key[i] ^ b
|
|
|
|
}
|
|
|
|
inner << data
|
|
|
|
inner_hash := hash_func(inner)
|
2022-04-15 14:35:35 +02:00
|
|
|
mut outer := []u8{cap: b_key.len}
|
2021-05-08 12:32:29 +02:00
|
|
|
for i, b in hmac.opad[..blocksize] {
|
2020-10-14 12:25:58 +02:00
|
|
|
outer << b_key[i] ^ b
|
|
|
|
}
|
|
|
|
outer << inner_hash
|
|
|
|
digest := hash_func(outer)
|
|
|
|
return digest
|
|
|
|
}
|
2020-10-14 16:21:43 +02:00
|
|
|
|
2021-01-23 13:33:49 +01:00
|
|
|
// equal compares 2 MACs for equality, without leaking timing info.
|
2022-03-06 18:01:22 +01:00
|
|
|
// Note: if the lengths of the 2 MACs are different, probably a completely different
|
2020-10-14 16:21:43 +02:00
|
|
|
// hash function was used to generate them => no useful timing information.
|
2022-04-15 14:35:35 +02:00
|
|
|
pub fn equal(mac1 []u8, mac2 []u8) bool {
|
2020-10-14 16:21:43 +02:00
|
|
|
return subtle.constant_time_compare(mac1, mac2) == 1
|
|
|
|
}
|