ThomasJohnson
ThomasJohnson

Reputation: 167

MD5 hash Go to Python

I have following code:

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))

}

If I run the code at: https://play.golang.org/ I get following output:

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

How can I replicate this in Python 3 ?

I tried following:

import hashlib 

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

Getting following output which doesn't match output given by Go:

a40f771ea430ae32dbc5e818387549d3

Thank you.

Upvotes: 2

Views: 956

Answers (3)

Keenan
Keenan

Reputation: 1403

Hi you just have to follow the examples from 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's %x in fmt prints "... base 16, with lower-case letters for a-f". More: https://golang.org/pkg/fmt/

Upvotes: 0

user12258482
user12258482

Reputation:

The comments in another answer state that the goal is match the Go code, even though the Go code does not compute the hash of the VIN.

Here's python3 code matches the Go code. This code base64 encodes the concatenation of the VIN and the MD5 initial value.

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}"}}')

The author of the Go code probably intended to write this:

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

Upvotes: 3

Burak Serdar
Burak Serdar

Reputation: 51572

You are using the hash incorrectly:

    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)) 

Upvotes: 2

Related Questions