The MD5 Message-Digest Algorithm is a widely used cryptographic hash function that produces a 128-bit (16-byte) hash value, used to ensure the integrity and consistency of information transmission.
This article will use the crypto/md5
package from the Golang standard library to implement MD5 hash calculation for strings;
Import necessary packages:
import (
"crypto/md5"
"encoding/hex"
)
crypto/md5
is the MD5 package in the standard library; while encoding/hex
is an encoding utility package that converts byte slices to strings.
Implementation:
func MD5(v string)string{
d := []byte(v)
m := md5.New()
m.Write(d)
return hex.EncodeToString(m.Sum(nil))
}
md5.New()
returns a hash.Hash
object; the hash.Hash
object defines a Sum
interface with the following prototype:
func Sum(data []byte) [Size]byte
Sum()
performs checksum calculation on the content stored internally in the hash.Hash
object, then appends it to data
to form a new byte slice, so data
is typically set to nil
.
The Write
interface of the hash.Hash
object only accepts byte slice data type;
Complete code:
package main
import (
"crypto/md5"
"encoding/hex"
"fmt"
)
func MD5(v string)string{
d := []byte(v)
m := md5.New()
m.Write(d)
return hex.EncodeToString(m.Sum(nil))
}
func main(){
fmt.Println(MD5("123456"))
}