Golang - MD5 Hash

In Go, you can calculate the MD5 hash of a string using the crypto/md5 package.

Here's an example of how you can calculate the MD5 hash of a string in Go:

package main

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

func main() {
	str := "Hello, World!" // The string for which you want to calculate the MD5 hash

	hash := md5.Sum([]byte(str)) // Calculate the MD5 hash of the string

	hashString := hex.EncodeToString(hash[:]) // Convert the hash to a hexadecimal string

	fmt.Println(hashString) // Print the MD5 hash string
}

In the above code, we first import the necessary packages: crypto/md5 for the MD5 hash algorithm and encoding/hex for encoding the hash result into a hexadecimal string.

Next, we define the string str for which we want to calculate the MD5 hash.

To calculate the MD5 hash, we use the md5.Sum() function, passing in the byte representation of the string using []byte(str).

The md5.Sum() function returns an array of 16 bytes, representing the MD5 hash. To convert it to a hexadecimal string, we use hex.EncodeToString() function, passing in the hash slice hash[:]. This function converts each byte to its two-character hexadecimal representation.

Finally, we print the MD5 hash string using fmt.Println().

When you run this code, it will output the MD5 hash string of the input string "Hello, World!".

author image

Founder of tarkiman.com, love programming and open source stuff. Subscribe him on Youtube Channel.

Comments