HMAC-SHA1在bash
问题描述:
答
我知道这不是你问什么了,但没有点重新发明轮子,写一个bash版。
您可以简单地使用openssl
命令生成脚本中的哈希值。
[[email protected]] echo -n "value" | openssl dgst -sha1 -hmac "key"
57443a4c052350a44638835d64fd66822f813319
或者干脆:
[[email protected]] echo -n "value" | openssl sha1 -hmac "key"
57443a4c052350a44638835d64fd66822f813319
记住使用-n
与echo
要不换行字符附加到字符串,并改变你的数据和散列。
这个命令来自哪个应该已经在你所选择的Linux/Unix,Cygwin和喜欢的安装(或易于安装)OpenSSL包。
请注意,旧版本的openssl
(例如RHEL4附带的版本)可能不提供-hmac
选项。
作为替代解决方案,但主要是为了证明,结果是一样的,我们也可以称之为PHP的hmac_sha1()
命令行:
[[email protected]]$ echo '<?= hash_hmac("sha1", "value", "key") ?>' | php
57443a4c052350a44638835d64fd66822f813319
答
这里是一个bash的功能就像hash_hmac
from PHP:
#!/bin/bash
function hash_hmac {
digest="$1"
data="$2"
key="$3"
shift 3
echo -n "$data" | openssl dgst "-$digest" -hmac "$key" "[email protected]"
}
# hex output by default
hash_hmac "sha1" "value" "key"
# raw output by adding the "-binary" flag
hash_hmac "sha1" "value" "key" -binary | base64
# other algos also work
hash_hmac "md5" "value" "key"
答
感谢您的hash_hmac功能!但这对我的应用程序来说还不够。在任何人想知道的情况下,我必须使用之前哈希结果的密钥重新哈希几次,因此是二进制输入。 (亚马逊AWS认证签名这样的创建。)
我需要那么什么是供应以某种方式,不会破坏算法二进制键的方式。后来我发现这一点:http://openssl.6102.n7.nabble.com/command-line-hmac-with-key-in-hex-td6754.html
斯蒂芬·亨森的答复要求hash_hmac功能十六进制格式返回值。因此,它需要呼应了以下内容:
$ echo -n "$data" | openssl dgst "-$digest" -hmac "$key" | sed -e 's/^.* //'
那么接下来的调用将需要提供密钥作为hexit:
$ echo -n "$data" | openssl dgst "-$digest" -mac HMAC -macopt "hexkey:$key" | sed -e 's/^.* //'
希望这有助于任何人,也许有人谁试图创建的bash脚本使AWS上的CloudFront条目失效(就像我一样!)(我还没有测试过,但我认为这是导致我的bash脚本无法正常工作的原因,而且我的PHP不能正常工作......)
OpenSSL的实现是很慢的。如果你偶尔需要这样做,那很好,但是如果你想要计算大量的哈希,你想调查不同的途径。 – Marcin
@Marcin:你可以引用一个来源吗? – sehe
[John The Ripper](http://www.openwall.com/john/)对于CPU实现非常快,而且它是开源的。 – Marcin