haskellhmacsha256

How to generate HMAC in Haskell Crypton, like with openssl HMAC?


Using Haskell crypton package, I'm trying to generate the same output as openssl dgst but can't figure out what I'm doing wrong. Please help.

openssl dgst:

$ echo "TheMessage" | openssl dgst -sha256 -mac HMAC -macopt key:"TheKey"
SHA2-256(stdin)= 7b2e5669f4a5fa30a3fa0e9147f8975883cddff77725c99a6db07395b9665974

crypton:

ghci> hmacGetDigest ( hmac ("TheKey" :: ByteString) ("TheMessage" :: ByteString) :: HMAC SHA256 )
39c17c48adbc2ea4d469af9ecb2569f921053843af2a0a7716b7a180b0cedff6

Thanks.


Solution

  • You've run into a common issue with testing out crypto code on the command line. The echo command adds a newline to the output, so you either need to hash "TheMessage\n" in the Haskell code or else use echo -n "TheMessage" to suppress the newline in your openssl test.

    Either:

    $ echo -n "TheMessage" | openssl dgst -sha256 -mac HMAC -macopt key:"TheKey"
    SHA2-256(stdin)= 39c17c48adbc2ea4d469af9ecb2569f921053843af2a0a7716b7a180b0cedff6
    
    ghci> hmacGetDigest (hmac ("TheKey" :: ByteString) ("TheMessage" :: ByteString) :: HMAC SHA256)
    39c17c48adbc2ea4d469af9ecb2569f921053843af2a0a7716b7a180b0cedff6
    

    or:

    $ echo "TheMessage" | openssl dgst -sha256 -mac HMAC -macopt key:"TheKey"
    SHA2-256(stdin)= 7b2e5669f4a5fa30a3fa0e9147f8975883cddff77725c99a6db07395b9665974
    
    ghci> > hmacGetDigest (hmac ("TheKey" :: ByteString) ("TheMessage\n" :: ByteString) :: HMAC SHA256)
    7b2e5669f4a5fa30a3fa0e9147f8975883cddff77725c99a6db07395b9665974