Erlang 计算 HMAC-SHA1 的例子?

发布于 2024-10-02 07:34:27 字数 1539 浏览 0 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

谎言 2024-10-09 07:34:27

为了扩展之前的答案,这里是 Python 中的 hmac 模块,使用 SHA-1 算法以及键“hello”和消息“world”:

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

这是 Erlang 中的等效项。我会使用一种更有效的方法将二进制 MAC 转换为典型代码中的十六进制摘要,但为了简洁起见,我使用了这个方法:

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"

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"
余厌 2024-10-09 07:34:27

crypto 模块中的 sha_mac 函数是 HMAC-SHA1:

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

它可能不匹配的原因是因为您可能将其与“hexdigest”而不是原始摘要数据进行比较。

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.

笑,眼淚并存 2024-10-09 07:34:27
string:to_lower(lists:flatten([[integer_to_list(N, 16) || <<N:4>> <= crypto:sha_mac("hello", "world")]])).
string:to_lower(lists:flatten([[integer_to_list(N, 16) || <<N:4>> <= crypto:sha_mac("hello", "world")]])).
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文