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
:
package main
import (
"fmt"
"hash/crc32"
)
func main() {
h := crc32.NewIEEE()
h.Write([]byte("test"))
v := h.Sum32()
fmt.Println(v)
}
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.
package main
import (
"fmt"
"hash/crc32"
"io/ioutil"
)
func getHash(filename string) (uint32, error) {
bs, err := ioutil.ReadFile(filename)
if err != nil {
return 0, err
}
h := crc32.NewIEEE()
h.Write(bs)
return h.Sum32(), nil
}
func main() {
h1, err := getHash("test1.txt")
if err != nil {
return
}
h2, err := getHash("test2.txt")
if err != nil {
return
}
fmt.Println(h1, h2, h1 == h2)
}
Let’s try a scenario, for example, if we fill in the files test1.txt
and test2.txt
as follows:
test1.txt
is filled withhello world
andtest2.txt
is filled withhello world santekno
–> data expectations from the two files are different so return (false)test1.txt
is filled withhello world
andtest2.txt
is filled withhello world
–> the data expectations from both files are the same, so return (true)