如何从 Golang 的字符串中获得 MD5散列?

这就是我如何开始从 string获得 md5散列的:

import "crypto/md5"


var original = "my string comes here"
var hash = md5.New(original)

但显然这不是它的工作原理,有人能提供一个工作样本吗?

108517 次浏览

From crypto/md5 doc:

package main


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


func main() {
h := md5.New()
io.WriteString(h, "The fog is getting thicker!")
fmt.Printf("%x", h.Sum(nil))
}

I found this solution to work well

package main


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


func main() {
var str string = "hello world"


hasher := md5.New()
hasher.Write([]byte(str))
fmt.Println(str)
fmt.Println(hex.EncodeToString(hasher.Sum(nil)))
}

I use this to MD5 hash my strings:

import (
"crypto/md5"
"encoding/hex"
)


func GetMD5Hash(text string) string {
hasher := md5.New()
hasher.Write([]byte(text))
return hex.EncodeToString(hasher.Sum(nil))
}
import (
"crypto/md5"
"encoding/hex"
)


func GetMD5Hash(text string) string {
hash := md5.Sum([]byte(text))
return hex.EncodeToString(hash[:])
}

Reference Sum,For me,following work well:

package main


import (
"crypto/md5"
"fmt"
)


func main() {
data := []byte("hello")
fmt.Printf("%x", md5.Sum(data))
}

Here is a function you could use to generate an MD5 hash:

// MD5 hashes using md5 algorithm
func MD5(text string) string {
algorithm := md5.New()
algorithm.Write([]byte(text))
return hex.EncodeToString(algorithm.Sum(nil))
}

I put together a group of those utility hash functions here: https://github.com/shomali11/util

You will find FNV32, FNV32a, FNV64, FNV65a, MD5, SHA1, SHA256 and SHA512

just another answer

// MD5 hashes using md5 algorithm
func MD5(text string) string {
data := []byte(text)
return fmt.Sprintf("%x", md5.Sum(data))
}