【发布时间】:2015-03-21 14:14:00
【问题描述】:
我有一个 Go 程序
package main
import (
"crypto/hmac"
"crypto/sha1"
"fmt"
)
func main() {
val := []byte("nJ1m4Cc3")
hasher := hmac.New(sha1.New, val)
fmt.Printf("%x\n", hasher.Sum(nil))
// f7c0aebfb7db2c15f1945a6b7b5286d173df894d
}
还有一个 Python (2.7) 程序试图重现 Go 代码(使用 crypto/hmac)
import hashlib
val = u'nJ1m4Cc3'
hasher = hashlib.new("sha1", val)
print hasher.hexdigest()
# d67c1f445987c52bceb8d6475c30a8b0e9a3365d
使用hmac 模块给了我不同的结果,但仍然与 Go 代码不同。
import hmac
val = 'nJ1m4Cc3'
h = hmac.new("sha1", val)
print h.hexdigest()
# d34435851209e463deeeb40cba7b75ef
为什么它们在相同的输入上使用相同的哈希时会打印不同的值?
【问题讨论】:
-
python 中的val不是字节...试试
val = b'nJ1m4Cc3' -
我的答案中包含了一种 Python 方法,可以重现您现在在 Go 中显示的内容。
hmac.new("sha1", val)是错误的:它提供了"sha1"为key,并且没有指定正确的摘要构造函数,因此该方法实际上在内部使用了 md5。您只需要仔细阅读文档并了解msg、key和digestmod参数在hmac.new()签名中的含义。 docs.python.org/2/library/hmac.html -
不客气,这是再次使用 Go 的好机会,我已经在我的系统上设置了一段时间 :-)。而且,以防万一,不要忘记接受答案:-)。
标签: python hash go cryptography sha1