Golang hash.Hash type examples

package hash

Hash is the common interface implemented by all hash functions.

Golang hash.Hash type usage examples

Example 1:

 // createMac creates a message authentication code (MAC).
 func createMac(h hash.Hash, value []byte) []byte {
 h.Write(value)
 return h.Sum(nil)
 }

Example 2:

 package main

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

 func main() {
 hash := md5.New()

 io.WriteString(hash, "I don't want anyone else to know about this string message!") // append into the hash

 fmt.Printf("%x \n", hash.Sum(nil))

 fmt.Printf("Size : %d \n", hash.Size())

 fmt.Printf("BlockSize : %d \n", hash.BlockSize())

 hash.Reset()

 // after reset
 fmt.Printf("%x \n", hash.Sum(nil))
 }

Example 3:

 func New() MultiHashContext {
 contexts := make(map[string]hash.Hash)
 contexts["adler32"] = adler32.New()
 contexts["crc32"] = crc32.NewIEEE()
 contexts["md5"] = md5.New()
 contexts["ripemd160"] = ripemd160.New()
 contexts["sha1"] = sha1.New()
 contexts["sha2-256"] = sha256.New()
 contexts["sha2-512"] = sha512.New()
 contexts["sha3-256"] = sha3.NewKeccak256()
 s := SizeWriter(0)
 return MultiHashContext{contexts: contexts, sw: &s}
 }

References :

https://github.com/chrisoei/multidigest/blob/master/multidigest.go

https://www.socketloop.com/tutorials/generate-md5-hash-of-a-string-go

http://golang.org/pkg/hash/#Hash

Advertisement