Getting to Know Hashes Cryptography in Golang
Hashes & Cryptography
The hash function takes a set of data and reduces it to a smaller fixed size. Hash is often used in programming for everything from searching data to easily detecting changes. The hash functions in Go are divided into two categories namely cryptographic and non-cryptographic. Non-cryptographic hash functions can be found under the hash package and include adler32, crc32, crc64 and fnv.
Here’s an example using crc32:
1package main
2import (
3 "fmt"
4 "hash/crc32"
5)
6func main() {
7 h := crc32.NewIEEE()
8 h.Write([]byte("test"))
9 v := h.Sum32()
10 fmt.Println(v)
11}Hash crc32 implements the Writer interface, so we can write bytes to it like any other Writer. Once we’ve written everything we want, we call Sum32() to return uint32. A common use for crc32 is to compare two files. If the Sum32 values for both files are the same, it is likely (though not 100% certain) that the files are the same. If the values are different then the files are definitely not the same.
The following compares two files using crc32 below.
1package main
2
3import (
4 "fmt"
5 "hash/crc32"
6 "io/ioutil"
7)
8
9func getHash(filename string) (uint32, error) {
10 bs, err := ioutil.ReadFile(filename)
11 if err != nil {
12 return 0, err
13 }
14 h := crc32.NewIEEE()
15 h.Write(bs)
16 return h.Sum32(), nil
17}
18func main() {
19 h1, err := getHash("test1.txt")
20 if err != nil {
21 return
22 }
23 h2, err := getHash("test2.txt")
24 if err != nil {
25 return
26 }
27 fmt.Println(h1, h2, h1 == h2)
28}test1.txt and test2.txt as follows:test1.txtis filled withhello worldandtest2.txtis filled withhello world santekno–> data expectations from the two files are different so return (false)test1.txtis filled withhello worldandtest2.txtis filled withhello world–> the data expectations from both files are the same, so return (true)