MD5哈希转到Python

我有以下代码:

package main

import (
    "crypto/md5"
    "encoding/json"
    "fmt"
)

type Payload struct {
    HVIN []byte `json:"hvin"`
}

func main() {
    vin := "1GBJC34R1VF063154"
    md5 := md5.New()
    md5Vin := md5.Sum([]byte(vin))
    payload := &Payload{
        HVIN: md5Vin,}
    b,_ := json.Marshal(payload)
    fmt.Printf("%s",string(b))

}

如果我在以下位置运行代码:https://play.golang.org/,则会得到以下输出:

{"hvin":"MUdCSkMzNFIxVkYwNjMxNTTUHYzZjwCyBOmACZjs+EJ+"}

如何在Python 3中复制它?

我尝试了以下操作:

import hashlib 

result = hashlib.md5(b'1GBJC34R1VF063154')
print(result.hexdigest()) 

获取以下与Go给出的输出不匹配的输出:

a40f771ea430ae32dbc5e818387549d3

谢谢。

zhipiao6365454 回答:MD5哈希转到Python

在另一个答案中,注释表明目标与Go代码匹配,即使Go代码没有计算VIN的哈希值。

这里的python3代码与Go代码匹配。此代码base64编码VIN和MD5初始值的串联。

vin := "1GBJC34R1VF063154"
b0 = vin.encode('utf-8')
b1 = hashlib.md5(b'').digest()
s =  base64.b64encode(b0 + b1).decode('ascii') // to match Go's encoding/json
print(f'{{"hvin":"{s}"}}')

Go代码的作者可能打算编写以下代码:

vin := "1GBJC34R1VF063154"
md5Vin := md5.Sum([]byte(vin))
payload := &Payload{
    HVIN: md5Vin[:],}
b,_ := json.Marshal(payload)
fmt.Printf("%s",string(b))
,

您使用的哈希值不正确:

    vin := "1GBJC34R1VF063154"
    md5 := md5.New()
    md5.Write([]byte(vin))
    md5Vin := md5.Sum(nil)
    // This should give a40f771ea430ae32dbc5e818387549d3
    fmt.Printf("%x",md5Vin)
    payload := &Payload{
        HVIN: md5Vin,}
    b,_ := json.Marshal(payload)
    // This will print the base64-encoded version of the hash
    fmt.Printf("%s",string(b)) 
,

嗨,您只需要遵循https://golang.org/pkg/crypto/md5/#example_New

中的示例

Golang

package main

import (
    "crypto/md5"
    "fmt"
    "io"
)

func main() {
    h := md5.New()
    vin := "1GBJC34R1VF063154"
    io.WriteString(h,vin)
    fmt.Printf("%x",h.Sum(nil)) // a40f771ea430ae32dbc5e818387549d3
}

Python

Python 3.6.8 (default,Oct  7 2019,12:59:55) 
[GCC 8.3.0] on linux
Type "help","copyright","credits" or "license" for more information.
>>> import hashlib 
>>> 
>>> result = hashlib.md5(b'1GBJC34R1VF063154')
>>> print(result.hexdigest()) 
a40f771ea430ae32dbc5e818387549d3

Golang在%x中的fmt打印“ ...基数16,a-f为小写字母”。 更多:https://golang.org/pkg/fmt/

本文链接:https://www.f2er.com/3108763.html

大家都在问