Generate checksum for a file in Go
With billions of files being downloaded and transferred across Internet everyday. Generating checksum is important component in proramming today to ensure that the files are not being tempered with. In this tutorial, we will learn how to generate MD5 checksum for a sample file in Go
checksum.go
package main
import (
"fmt"
"io"
"os"
"math"
"crypto/md5"
)
const filechunk = 8192 // we settle for 8KB
func main() {
file, err := os.Open("utf8.txt")
if err != nil {
panic(err.Error())
}
defer file.Close()
// calculate the file size
info, _ := file.Stat()
filesize := info.Size()
blocks := uint64(math.Ceil(float64(filesize) / float64(filechunk)))
hash := md5.New()
for i := uint64(0); i < blocks; i++ {
blocksize := int(math.Min(filechunk, float64(filesize-int64(i*filechunk))))
buf := make([] byte, blocksize)
file.Read(buf)
io.WriteString(hash, string(buf)) // append into the hash
}
fmt.Printf("%s checksum is %x\n",file.Name(), hash.Sum(nil))
}
Output : >go run checksum.go
utf8.txt checksum is c3882b3e45e88ba87617f44ce1e7611d
This example uses the md5 crypto and of course you can just replace it with SHA1, SHA256 easily by changing the crypto package.
References :
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+35k Golang : Display float in 2 decimal points and rounding up or down
+8k Golang : Serving HTTP and Websocket from different ports in a program example
+11k Golang : Encrypt and decrypt data with x509 crypto
+8.3k Golang : ffmpeg with os/exec.Command() returns non-zero status
+13.5k Golang : Rename directory
+19.6k Golang : Create and resolve(read) symbolic links
+4.9k Golang : How to search a list of records or data structures
+9.9k Golang : Intercept and process UNIX signals example
+16.3k Golang : [json: cannot unmarshal object into Go value of type]
+6.1k Golang : Check if one string(rune) is permutation of another string(rune)
+16.1k Golang : How to remove certain lines from a file
+53.2k Golang : Unmarshal JSON from http response