Created
August 26, 2015 22:08
-
-
Save josephspurrier/e714fa55ae4c5ddfa668 to your computer and use it in GitHub Desktop.
SHA1 Hash Generator in Golang
This file contains hidden or 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 | |
import ( | |
"crypto/sha1" | |
"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: sha1.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() | |
hash := sha1.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
With that code (buffer+read+write):
(SHA1: 8b48ae8cc9e88214577f6e6de30bafd9756bdec8) = 6.035ms
Using only "io.Copy(hash, file)"...
(SHA1: 8b48ae8cc9e88214577f6e6de30bafd9756bdec8) = 3.0308ms