sha256

Pure Haskell SHA-256, HMAC-SHA256 (docs.ppad.tech/sha256).
git clone git://git.ppad.tech/sha256.git
Log | Files | Refs | README | LICENSE

commit 7344124c3ca3870d9de316c666c9d3cc9fd33546
parent 38de84385a4d9b4e3582d9755d833e70eb14116a
Author: Jared Tobin <jared@jtobin.io>
Date:   Sun, 13 Oct 2024 13:26:50 +0400

lib: don't call hmac_lazy in strict

This wasn't a huge deal, but sort of messes with profiling.

Diffstat:
Mlib/Crypto/Hash/SHA256.hs | 23++++++++++++++++++-----
1 file changed, 18 insertions(+), 5 deletions(-)

diff --git a/lib/Crypto/Hash/SHA256.hs b/lib/Crypto/Hash/SHA256.hs @@ -420,6 +420,10 @@ hash_lazy bl = cat (go iv (pad_lazy bl)) where -- HMAC ----------------------------------------------------------------------- -- https://datatracker.ietf.org/doc/html/rfc2104#section-2 +data KeyAndLen = KeyAndLen + {-# UNPACK #-} !BS.ByteString + {-# UNPACK #-} !Int + -- | Produce a message authentication code for a strict bytestring, -- based on the provided (strict, bytestring) key, via SHA-256. -- @@ -434,11 +438,20 @@ hmac :: BS.ByteString -- ^ key -> BS.ByteString -- ^ text -> BS.ByteString -hmac k = hmac_lazy k . BL.fromStrict - -data KeyAndLen = KeyAndLen - {-# UNPACK #-} !BS.ByteString - {-# UNPACK #-} !Int +hmac mk text = + let step1 = k <> BS.replicate (64 - lk) 0x00 + step2 = BS.map (B.xor 0x36) step1 + step3 = step2 <> text + step4 = hash step3 + step5 = BS.map (B.xor 0x5C) step1 + step6 = step5 <> step4 + in hash step6 + where + !(KeyAndLen k lk) = + let l = BS.length mk + in if l > 64 + then KeyAndLen (hash mk) 32 + else KeyAndLen mk l -- | Produce a message authentication code for a lazy bytestring, based -- on the provided (strict, bytestring) key, via SHA-256.