4 min read

A hashing algorithm is a cryptographic hash technique. It is a scientific calculation that maps data with a subjective size to a hash with a settled size. It’s intended to be a single direction function, that you cannot alter. This article covers hash functions and the implementation of a hashing algorithm in Golang.

This article is taken from the book Learn Data Structures and Algorithms with Golang by Bhagvan Kommadi. Complete with hands-on tutorials, this book will guide you in using the best data structures and algorithms for problem-solving in Golang.

Install Go version 1.10 for your OS. The GitHub URL for the code in this article is available here.

The hash functions

Hash functions are used in cryptography and other areas. These data structures are presented with code examples related to cryptography. There are two ways to implement a hash function in Go: with crc32 or sha256. Marshaling (changing the string to an encoded form) saves the internal state, which is used for other purposes later. A BinaryMarshaler (converting the string into binary form) example is explained in this section:


//main package has examples shown
// in Hands-On Data Structures and algorithms with Go book
package main
// importing bytes, crpto/sha256, encoding, fmt and log package
import (
 "bytes"
 "crypto/sha256"
 "encoding"
 "fmt"
 "log"
 "hash"
)

The main method creates a binary marshaled hash of two example strings. The hashes of the two strings are printed. The sum of the first hash is compared with the second hash using the equals method on bytes. This is shown in the following code:

//main method
func main() {
 const (
 example1 = "this is a example "
 example2 = "second example"
 )
 var firstHash hash.Hash
 firstHash = sha256.New()
 firstHash.Write([]byte(example1))
 var marshaler encoding.BinaryMarshaler
 var ok bool
 marshaler, ok = firstHash.(encoding.BinaryMarshaler)
 if !ok {
 log.Fatal("first Hash is not generated by encoding.BinaryMarshaler")
 }
 var data []byte
 var err error
 data, err = marshaler.MarshalBinary()
 if err != nil {
 log.Fatal("failure to create first Hash:", err)
 }
 var secondHash hash.Hash
 secondHash = sha256.New()
var unmarshaler encoding.BinaryUnmarshaler
 unmarshaler, ok = secondHash.(encoding.BinaryUnmarshaler)
 if !ok {
 log.Fatal("second Hash is not generated by encoding.BinaryUnmarshaler")
 }
 if err := unmarshaler.UnmarshalBinary(data); err != nil {
 log.Fatal("failure to create hash:", err)
 }
 firstHash.Write([]byte(example2))
 secondHash.Write([]byte(example2))
 fmt.Printf("%x\n", firstHash.Sum(nil))
 fmt.Println(bytes.Equal(firstHash.Sum(nil), secondHash.Sum(nil)))
}

Run the following command to execute the hash.go file:

go run hash.go

The output is as follows:

Hash implementation in Go

Hash implementation in Go has crc32 and sha256 implementations. An implementation of a hashing algorithm with multiple values using an XOR transformation is shown in the following code snippet. The CreateHash function takes a byte array, byteStr, as a parameter and returns the sha256 checksum of the byte array:

//main package has examples shown
// in Go Data Structures and algorithms book
package main

// importing fmt package
import (
"fmt"
"crypto/sha1"
"hash"
)

//CreateHash method
func CreateHash(byteStr []byte) []byte {
var hashVal hash.Hash
hashVal = sha1.New()
hashVal.Write(byteStr)

var bytes []byte

bytes = hashVal.Sum(nil)
return bytes
}

In the following sections, we will discuss the different methods of hash algorithms.

The CreateHashMutliple method

The CreateHashMutliple method takes the byteStr1 and byteStr2 byte arrays as parameters and returns the XOR-transformed bytes value, as follows:

// Create hash for Multiple Values method
func CreateHashMultiple(byteStr1 []byte, byteStr2 []byte) []byte {
  return xor(CreateHash(byteStr1), CreateHash(byteStr2))
}

The XOR method

The xor method takes the byteStr1 and byteStr2 byte arrays as parameters and returns the XOR-transformation result, as follows:

The main method

The main method invokes the createHashMutliple method, passing Check and Hash as string parameters, and prints the hash value of the strings, as follows:

// main method
func main() {

  var bytes []byte
  bytes = CreateHashMultiple([]byte("Check"), []byte("Hash"))

  fmt.Printf("%x\n", bytes)
}

Run the following command to execute the hash.go file:

go run hash.go

The output is as follows:

In this article, we discussed hashing algorithms in Golang alongside code examples and performance analysis.

To know more about network representation using graphs and sparse matrix representation using a list of lists in Go, read our book Learn Data Structures and Algorithms with Golang.

Read Next

Go User Survey 2018 results: Golang goes from strength to strength, as more engineers than ever are using it at work.

State of Go February 2019 – Golang developments report for this month released

The Golang team has started working on Go 2 proposals


Subscribe to the weekly Packt Hub newsletter. We'll send you the results of our AI Now Survey, featuring data and insights from across the tech landscape.