How to Get a MD5 Hash from a String in Go
Created
Modified
Using Sum Function
The md5.Sum()
function returns the MD5 checksum of the data.
The following example should cover whatever you are trying to do:
package main
import (
"crypto/md5"
"encoding/hex"
"fmt"
)
func main() {
b := []byte("Hello")
out := md5.Sum(b)
fmt.Printf("%x\n", out)
// EncodeToString
fmt.Println(hex.EncodeToString(out[:]))
}
8b1a9953c4611296a827abf8c47804d7 8b1a9953c4611296a827abf8c47804d7
Using New Function
New returns a new hash.Hash computing the MD5 checksum. The Hash also implements encoding.BinaryMarshaler and encoding.BinaryUnmarshaler to marshal and unmarshal the internal state of the hash.
For example,
package main
import (
"crypto/md5"
"fmt"
"io"
)
func main() {
h := md5.New()
io.WriteString(h, "Hello")
io.WriteString(h, "Word")
fmt.Printf("%x\n", h.Sum(nil))
}
04b6f86d49716af8d4f2edf01a309fc8
Generate MD5 checksum of a file. See the following example:
package main
import (
"crypto/md5"
"fmt"
"io"
"os"
)
func main() {
f, err := os.Open("ins.txt")
if err != nil {
// log.Fatal(err)
}
defer f.Close()
h := md5.New()
if _, err := io.Copy(h, f); err != nil {
// log.Fatal(err)
}
fmt.Printf("%x\n", h.Sum(nil))
}
3dca0fa76621281bfb7ffab47c860502