How to get a MD5 hash from a string in Golang?

CryptographyMd5Go

Cryptography Problem Overview


This is how I started to get a md5 hash from a string:

import "crypto/md5"

var original = "my string comes here"
var hash = md5.New(original)

But obviously this is not how it works. Can someone provide me a working sample for this?

Cryptography Solutions


Solution 1 - Cryptography

Reference Sum,For me,following work well:

package main

import (
	"crypto/md5"
	"fmt"
)

func main() {
	data := []byte("hello")
	fmt.Printf("%x", md5.Sum(data))
}

Solution 2 - Cryptography

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

func GetMD5Hash(text string) string {
   hash := md5.Sum([]byte(text))
   return hex.EncodeToString(hash[:])
}

Solution 3 - Cryptography

I found this solution to work well

package main

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

func main() {
	var str string = "hello world"

	hasher := md5.New()
	hasher.Write([]byte(str))
	fmt.Println(str)
	fmt.Println(hex.EncodeToString(hasher.Sum(nil)))
}

Solution 4 - Cryptography

From crypto/md5 doc:

package main

import (
	"crypto/md5"
	"fmt"
	"io"
)

func main() {
	h := md5.New()
	io.WriteString(h, "The fog is getting thicker!")
	fmt.Printf("%x", h.Sum(nil))
}

Solution 5 - Cryptography

I use this to MD5 hash my strings:

import (
    "crypto/md5"
    "encoding/hex"
)
 
func GetMD5Hash(text string) string {
    hasher := md5.New()
    hasher.Write([]byte(text))
    return hex.EncodeToString(hasher.Sum(nil))
}

Solution 6 - Cryptography

Here is a function you could use to generate an MD5 hash:

// MD5 hashes using md5 algorithm
func MD5(text string) string {
    algorithm := md5.New()
	algorithm.Write([]byte(text))
    return hex.EncodeToString(algorithm.Sum(nil))
}

I put together a group of those utility hash functions here: https://github.com/shomali11/util

You will find FNV32, FNV32a, FNV64, FNV65a, MD5, SHA1, SHA256 and SHA512

Solution 7 - Cryptography

just another answer

// MD5 hashes using md5 algorithm
func MD5(text string) string {
	data := []byte(text)
	return fmt.Sprintf("%x", md5.Sum(data))
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncringeView Question on Stackoverflow
Solution 1 - CryptographyAlanView Answer on Stackoverflow
Solution 2 - CryptographyavivView Answer on Stackoverflow
Solution 3 - Cryptographyuser387049View Answer on Stackoverflow
Solution 4 - CryptographyStephen HsuView Answer on Stackoverflow
Solution 5 - CryptographysergsergView Answer on Stackoverflow
Solution 6 - CryptographyRaed ShomaliView Answer on Stackoverflow
Solution 7 - CryptographyYuseferiView Answer on Stackoverflow