I'm trying to implement HMAC in Elm,
but I can't seem to figure out what I'm doing wrong here.
Some help would be greatly appreciated 🙏
type alias HashFunction =
String -> String
encrypt64 : HashFunction -> String -> String -> String
encrypt64 =
encrypt 64
encrypt : Int -> HashFunction -> String -> String -> String
encrypt blockSize hasher message key =
let
keySize =
String.length key
keyWithCorrectSize =
if keySize > blockSize then
hexStringToUtf8String (hasher key)
else if keySize < blockSize then
String.padRight blockSize (Char.fromCode 0) key
else
key
keyCodePoints =
keyWithCorrectSize
|> String.toList
|> List.map Char.toCode
partA =
keyCodePoints
|> List.map (Bitwise.xor 54 >> Char.fromCode)
|> String.fromList
partB =
keyCodePoints
|> List.map (Bitwise.xor 92 >> Char.fromCode)
|> String.fromList
in
message
|> String.append partA
|> hasher
|> hexStringToUtf8String
|> String.append partB
|> hasher
-- Utils
hexStringToUtf8String : String -> String
hexStringToUtf8String input =
input
|> String.toList
|> List.Extra.greedyGroupsOf 2
|> List.map (String.fromList >> hexStringToUtf8Char)
|> String.fromList
hexStringToUtf8Char : String -> Char
hexStringToUtf8Char input =
case Hex.fromString input of
Ok v ->
Char.fromCode v
Err err ->
Debug.crash err
You can find the related code here: https://github.com/icidasset/ongaku-ryoho/blob/master/src/App/Sources/Crypto/Hmac.elm (which includes doc tests)
edit: To be more clear... my current code here doesn't output a valid HMAC,
and I would like to know why.
Looking at the Elm SHA library, I think the problem (or at least a problem) is that the output from the hash is hex encoded. HMAC calls the hash function twice, feeding the first output back into the second call, and this needs to be the raw SHA bytes, rather than a hex string.
So you need to decode the hex output from the first call to hasher, after it is applied to partA.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With