0xBF
0xBF

0xBF

Go Cheatsheet - Hash Function

0xBF's photo
0xBF

Published on Apr 21, 2021

1 min read

Hash Function

From Go's standard "crypto" library, we can easily calculate hash value with md5, sha1, sha256, sha512 function.

package main

import (
    "crypto/md5"
    "crypto/sha1"
    "crypto/sha256"
    "crypto/sha512"
    "encoding/hex"
    "fmt"
)

func simpleMD5Hex(b []byte) string {
    return fmt.Sprintf("%x", md5.Sum(b))
}

func simpleSha1Hex(b []byte) string {
    return fmt.Sprintf("%x", sha1.Sum(b))
}

func simpleSha256Hex(b []byte) string {
    return fmt.Sprintf("%x", sha256.Sum256(b))
}

func simpleSha512hex(b []byte) string {
    return fmt.Sprintf("%x", sha512.Sum512(b))
}

func md5hex(data []byte) string {
    h := md5.New()
    h.Write(data)
    b := h.Sum(nil)
    return hex.EncodeToString(b)
}

func sha1hex(data []byte) string {
    h := sha1.New()
    h.Write(data)
    b := h.Sum(nil)
    return hex.EncodeToString(b)
}

func sha256hex(data []byte) string {
    h := sha256.New()
    h.Write(data)
    b := h.Sum(nil)
    return hex.EncodeToString(b)
}

func sha512hex(data []byte) string {
    h := sha512.New()
    h.Write(data)
    b := h.Sum(nil)
    return hex.EncodeToString(b)
}

func main() {
    data := []byte("hello world")
    fmt.Println("MD5 hex", md5hex(data))
    fmt.Println("Sha1 hex", sha1hex(data))
    fmt.Println("Sha256 hex", sha256hex(data))
    fmt.Println("Sha512 hex", sha512hex(data))
}

Result:

MD5 hex 5eb63bbbe01eeed093cb22bb8f5acdc3
Sha1 hex 2aae6c35c94fcfb415dbe95f408b9ce91ee846ed
Sha256 hex b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9
Sha512 hex 309ecc489c12d6eb4cc40f50c902f2b4d0ed77ee511a7c7a9bcd3ca86d4cd86f989dd35bc5ff499670da34255b45b0cfd830e81f605dcf7dc5542e93ae9cd76f
 
Share this