How to work with Hashes and Cryptography in Go

Hashing

The non-cryptographic hash functions include adler32, crc32, crc64, and fnv. Here’s an example using crc32:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
package main

import (
	"fmt"
	"hash/crc32"
)

func main() {
	h := crc32.NewIEEE()

        // Write to the hash object
	h.Write([]byte("Hello, World"))
        
        // Make a buffer of bytes from the hashed text
	buffer := h.Sum([]byte{})

        // Convert the buffer to string
	hashStr := string(bufferStr)
	fmt.Println(hashStr)
}

SHA Hashes

With hashing algorithms like SHA, it is extremely difficult to recover the original message. SHA is usually used in security, like proving if the file is original or not.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
package main

import (
	"crypto/sha1"
	"fmt"
)

func main() {
	sha := sha1.New()
	sha.Write([]byte("Hello, World"))
	shaBuffer := sha.Sum([]byte{})
	shaStr := string(shaBuffer)
	fmt.Println(shaStr)
}

Example