create a md5 hash from a string in go

Here's an example of how to generate an MD5 hash from a string in Go:

main.go
package main

import (
	"crypto/md5"
	"fmt"
)

func main() {
	str := "hello world"

	// create a new MD5 hash
	hash := md5.New()

	// write our string to the hash
	hash.Write([]byte(str))

	// get the resulting hash value as a byte slice
	hashBytes := hash.Sum(nil)

	// convert our byte slice to a string
	hashStr := fmt.Sprintf("%x", hashBytes)

	fmt.Println(hashStr) // output: 5eb63bbbe01eeed093cb22bb8f5acdc3
}
416 chars
25 lines

In this code, we first create a new md5 hash using md5.New(). We then write our string to the hash using hash.Write([]byte(str)). Finally, we get the resulting hash value as a byte slice using hash.Sum(nil) and convert it to a string using fmt.Sprintf("%x", hashBytes). The resulting hash string is then printed to the console.

related categories

gistlibby LogSnag