11

Any examples or libraries to caculate HMAC-SHA1 in Erlang?

I tried Crypto Module, but apparently doesn't match exactly. Any examples?

barata7
  • 338
  • 1
  • 5
  • 13

3 Answers3

22

To expand on the previous answer, here is the hmac module in Python using the SHA-1 algorithm with the key 'hello' and the message 'world':

>>> import hashlib
>>> import hmac
>>> hmac.HMAC(key='hello', msg='world', digestmod=hashlib.sha1).hexdigest()
'8a3a84bcd0d0065e97f175d370447c7d02e00973'

Here's the equivalent in Erlang. I'd use a more efficient method to convert the binary MAC to a hex digest in typical code, but I used this one for brevity:

1> crypto:start().
ok
2> <<Mac:160/integer>> = crypto:hmac(sha, <<"hello">>, <<"world">>).
<<138,58,132,188,208,208,6,94,151,241,117,211,112,68,124,
  125,2,224,9,115>>
3> lists:flatten(io_lib:format("~40.16.0b", [Mac])). 
"8a3a84bcd0d0065e97f175d370447c7d02e00973"
  • 1
    crypto:sha_mac/2 is deprecated, replaced with crypto:hmac/3 You're better of this way: `<> = crypto:hmac(sha,<<"hello">>, <<"world">>).` – Berzemus Jan 14 '14 at 11:14
  • 1
    That interface did not exist in 2010, when this answer was written. I believe this API was added rather recently in an R16 release. You're welcome to propose an edit. – YOUR ARGUMENT IS VALID Jan 15 '14 at 21:11
2

The sha_mac function in the crypto module is HMAC-SHA1:

http://www.erlang.org/doc/man/crypto.html#sha_mac-2

The reason it might not match is because you're probably comparing it to a "hexdigest", not the raw digest data.

0
string:to_lower(lists:flatten([[integer_to_list(N, 16) || <<N:4>> <= crypto:sha_mac("hello", "world")]])).
wudeng
  • 795
  • 5
  • 8