0

I know there is hashlib in Python, but I want to achieve the same result as in Go below:

package main

import (
    "crypto/md5"
    "fmt"
)

func main() {
    data := []byte("12345")
    fmt.Println("sum ", md5.Sum(data))
}

As func md5.Sum described, it calculates "MD5 checksum of the data". However, I don't find any similar function in Python.

Is there any way to achieve md5.Sum in Python as in Go?

The output of program above is a slice other than a string:

sum  [32 44 185 98 172 89 7 91 150 75 7 21 45 35 75 112]
stevenferrer
  • 2,504
  • 1
  • 22
  • 33
  • 3
    See https://stackoverflow.com/questions/5297448/how-to-get-md5-sum-of-a-string – Polymer Oct 18 '17 at 06:43
  • thx, I have seen that, it couldn't do md5.sum for data – user3342796 Oct 18 '17 at 06:47
  • 1
    Here's a one-liner: `from hashlib import md5;print(md5(b'12345').hexdigest())`. Output: `827ccb0eea8a706c4c34a16891f84e7b`. If you do `echo -n '12345' | md5sum` in Bash you get the same output. – PM 2Ring Oct 18 '17 at 06:51
  • thanks, please check my output part: the output for Go is a list other than a string ,so simply call python API not work – user3342796 Oct 18 '17 at 06:55
  • 1
    MD5 outputs 16 bytes. Your Go code is outputting those 16 bytes as numbers in the range 0..255. And it's easy to get Python to create a list of numbers like that from the MD5 sum. But I don't see why your Go code prints those numbers from "12345" . Can you show how the original `data` prints? – PM 2Ring Oct 18 '17 at 07:02
  • I just tested my code with `b"These pretzels are making me thirsty."`, the same data as in the example in the Go docs you linked, and I get the same output as what's printed there, `b0804ec967f48520697662a204f5fe72`, or in numeric form `[176, 128, 78, 201, 103, 244, 133, 32, 105, 118, 98, 162, 4, 245, 254, 114]` – PM 2Ring Oct 18 '17 at 07:13

1 Answers1

0

Based on PM 2Ring's solution, here is a working program,

from hashlib import md5

hexv = md5(b'12345').hexdigest()
l = [str(int(i+j,16)) for i, j in zip(hexv[::2], hexv[1::2])]
print("sum [" + ", ".join(l)+"]")

This prints,

sum [130, 124, 203, 14, 234, 138, 112, 108, 76, 52, 161, 104, 145, 248, 78, 123]
Jayson Chacko
  • 2,388
  • 1
  • 11
  • 16
  • 1
    There's a _much_ easier way to do that conversion! Just convert the `bytes` returned by `md5` into a list, like this: `list(md5(b'12345').digest())`, or in Python 2 `list(bytearray(md5(b'12345').digest()))`. FWIW, I didn't post a full answer because I'm _still_ waiting for the OP to clarify why they get `[32 44 185 98 172 89 7 91 150 75 7 21 45 35 75 112]` instead of the list that you got. – PM 2Ring Oct 18 '17 at 09:57