MD5 Encoding in Golang

You can use the crypto/md5 [docs] package in Go to perform MD5 encoding on a string. We have an example function below, it will take your string and write it as a hash. Then convert that binary back into a hexadecimal string using Sprintf.

Note: There are more modern approaches than md5 these days - and it isn’t recommended for many things, but definitely not password hashing.

Here’s an example of how to use it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package main

import (
	"crypto/md5"
	"fmt"
)

func main() {

	input := "welcome to gophercoding.com"

	output := md5Encode(input)

	fmt.Println(input, "=", output)
}

// md5Encode will take a string and encode it as md5.
func md5Encode(input string) string {

	// Create a new hash & write input string
	hash := md5.New()
	_, _ = hash.Write([]byte(input))

	// Get the resulting encoded byte slice
	md5 := hash.Sum(nil)

	// Convert the encoded byte slice to a string
	return fmt.Sprintf("%x", md5)
}

Example In Action

golang write to csv