Skip to content
heff

std.hmac

HMAC, the message authentication code of RFC 2104: a hash of a message and a secret key, which only one who has the key can make, so that a message whose code is right was not made or changed by anyone else. It is of any hash of blocks, given with its block size in bytes: std.sha256’s, std.sha1’s and std.md5’s are 64.

import bytes as Bytes
import std.hmac as HMAC
import std.sha256 as SHA256
-- | the code a webhook's body is signed with, by the key it shares
signature : Bytes -> Bytes -> Bytes
signature key body = HMAC.mac SHA256.digest 64 key body

mac

mac : (Bytes -> Bytes) -> Int -> Bytes -> Bytes -> Bytes

mac hash blockSize key message: the HMAC of message by key with hash, whose blocks are blockSize bytes. A key longer than a block is hashed first; a shorter one is padded with zeros. (Tests 1, 2 and 6 of RFC 4231.)

>>> mac SHA256.digest 64 (Bytes.fromList (List.replicate 20 0x0b)) (Bytes.fromString "Hi There") == b[0xb0344c61d8db3853::64, 0x5ca8afceaf0bf12b::64, 0x881dc200c9833da7::64, 0x26e9376c2e32cff7::64]
True
>>> mac SHA256.digest 64 (Bytes.fromString "Jefe") (Bytes.fromString "what do ya want for nothing?") == b[0x5bdcc146bf60754e::64, 0x6a042426089575c7::64, 0x5a003f089d273983::64, 0x9dec58b964ec3843::64]
True
>>> mac SHA256.digest 64 (Bytes.fromList (List.replicate 131 0xaa)) (Bytes.fromString "Test Using Larger Than Block-Size Key - Hash Key First") == b[0x60e431591ee0b67f::64, 0x0d8a26aacbf5b77f::64, 0x8e0bc6213728c514::64, 0x0546040f0ee37f54::64]
True