Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python与Go散列的区别_Python_Hash_Go_Cryptography_Sha1 - Fatal编程技术网

Python与Go散列的区别

Python与Go散列的区别,python,hash,go,cryptography,sha1,Python,Hash,Go,Cryptography,Sha1,我有一个围棋计划 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

我有一个围棋计划

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

使用
hmac
模块会给我一个不同的结果,但仍然与Go代码不同

import hmac
val = 'nJ1m4Cc3'
h = hmac.new("sha1", val)
print h.hexdigest()
# d34435851209e463deeeb40cba7b75ef

当它们在同一输入上使用相同的哈希值时,为什么要打印不同的值?

您必须确保

  • 这两种情况下的输入是等效的
  • 两种情况下的处理方法是等效的
在这两种情况下,输入应该是相同的二进制blob。在Python程序中,您定义了一个unicode对象,而不控制其二进制表示形式。将
u
前缀替换为
b
,您就没事了(这是在Python 2.7和3中定义字节序列的明确方式)。这不是实际问题,但最好在这里明确

问题在于在Go和Python实现中应用了不同的方法。

鉴于Python是参考 在Go中,根本不需要导入
“crypto/hmac”
,在Python中,您只需构建数据的SHA1散列。在Go中,等效值为:

package main

import (
    "crypto/sha1"
    "fmt"
)

func main() {
    data := []byte("nJ1m4Cc3")
    fmt.Printf("%x", sha1.Sum(data))
}
测试和输出:

go run hashit.go
d67c1f445987c52bceb8d6475c30a8b0e9a3365d
这将复制第一个Python代码段创建的内容

编辑:我简化了Go代码,使Python看起来不那么优雅。围棋在这里也很优雅:-)

既然围棋是参考 测试和输出:

python hashit.py
f7c0aebfb7db2c15f1945a6b7b5286d173df894d

这将复制Go代码段创建的内容。但是,我不确定当使用空消息时HMAC的加密意义。

python中的val不是字节。。。请尝试
val=b'nJ1m4Cc3'
我的答案中包含了一个Python方法,它复制了您在Go now中显示的内容
hmac.new(“sha1”,val)
是错误的:它将
“sha1”
作为
键提供,并且没有指定正确的摘要构造函数,因此此方法实际上在内部使用md5。您只需仔细阅读文档,了解
msg
digestmod
参数在
hmac.new()
签名中的含义。不客气,这是再次使用Go的好机会,我已经在我的系统上设置了一段时间:-)。而且,以防万一,别忘了接受答案:-)。我正试图与我使用哈希运算的现有密码保持一致,而且节点的密码哈希运算使用
hasher:=hmac.New(sha1.New,val)
行。但是谢谢!
import hmac
import hashlib

data = b'nJ1m4Cc3'
h = hmac.new(key=data, digestmod=hashlib.sha1)
print h.hexdigest()
python hashit.py
f7c0aebfb7db2c15f1945a6b7b5286d173df894d