Created
October 29, 2016 15:31
-
-
Save Gitart/62af00658fd8e67619b12bf60f96bc39 to your computer and use it in GitHub Desktop.
Md5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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