In Go, the crypto/md5
package provides a simple way to calculate the MD5 hash of a given string or byte slice.
Here is an example program that demonstrates how to use the crypto/md5
package:
package main
import (
"crypto/md5"
"encoding/hex"
"fmt"
)
func main() {
data := []byte("hello world")
// Calculate the MD5 hash
hash := md5.Sum(data)
// Convert the hash to a hex string
hexHash := hex.EncodeToString(hash[:])
fmt.Println(hexHash) // Output: 5eb63bbbe01eeed093cb22bb8f5acdc3
}
In this example, we first define a byte slice containing the data we want to hash ("hello world"
). We then call the md5.Sum()
function with this data as input. This function returns an array of 16 bytes representing the MD5 hash.
To convert this byte array to a human-readable hex string, we use Go’s built-in hex.EncodeToString()
function. Finally, we print out the resulting hex string ("5eb63bbbe01eeed093cb22bb8f5acdc3"
) using fmt.Println()
.