Skip to content

Instantly share code, notes, and snippets.

@josephspurrier
Created August 26, 2015 21:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save josephspurrier/90e957f1277964f26852 to your computer and use it in GitHub Desktop.
Save josephspurrier/90e957f1277964f26852 to your computer and use it in GitHub Desktop.
MD5 Hash Generator in Golang
package main
// Source: https://www.socketloop.com/tutorials/how-to-generate-checksum-for-file-in-go
import (
"crypto/md5"
"fmt"
"io"
"math"
"os"
)
// 8KB
const filechunk = 8192
func main() {
// Ensure the file argument is passed
if len(os.Args) != 2 {
fmt.Println("Please use this syntax: md5.exe file.txt")
return
}
// Open the file for reading
file, err := os.Open(os.Args[1])
if err != nil {
fmt.Println("Cannot find file:", os.Args[1])
return
}
defer file.Close()
// Get file info
info, err := file.Stat()
if err != nil {
fmt.Println("Cannot access file:", os.Args[1])
return
}
// Get the filesize
filesize := info.Size()
// Calculate the number of blocks
blocks := uint64(math.Ceil(float64(filesize) / float64(filechunk)))
// Start hash
hash := md5.New()
// Check each block
for i := uint64(0); i < blocks; i++ {
// Calculate block size
blocksize := int(math.Min(filechunk, float64(filesize-int64(i*filechunk))))
// Make a buffer
buf := make([]byte, blocksize)
// Make a buffer
file.Read(buf)
// Write to the buffer
io.WriteString(hash, string(buf))
}
// Output the results
fmt.Printf("%x\n", hash.Sum(nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment