Skip to content

Instantly share code, notes, and snippets.

@daniel-woods
Created July 11, 2018 18:05
Show Gist options
  • Save daniel-woods/dd3a2ce2fb8047dccf3f9348bb2f65ea to your computer and use it in GitHub Desktop.
Save daniel-woods/dd3a2ce2fb8047dccf3f9348bb2f65ea to your computer and use it in GitHub Desktop.
File Checksums in Go
// ./hash_file.go sha256 /path/to/file
package main
import (
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"fmt"
"io"
"log"
"os"
)
func main() {
// Open / Read the file to memory
if len(os.Args) == 3 {
file, err := os.Open(os.Args[2])
if err != nil {
log.Fatal(err)
}
defer file.Close()
// Check os.Args[1] for the hashing algorithm
if os.Args[1] == "sha256" {
hash := sha256.New()
if _, err := io.Copy(hash, file); err != nil {
log.Fatal(err)
}
fmt.Printf("%x %v\n", hash.Sum(nil), os.Args[2])
} else if os.Args[1] == "sha1" {
hash := sha1.New()
if _, err := io.Copy(hash, file); err != nil {
log.Fatal(err)
}
fmt.Printf("%x %v\n", hash.Sum(nil), os.Args[2])
} else if os.Args[1] == "md5" {
hash := md5.New()
if _, err := io.Copy(hash, file); err != nil {
log.Fatal(err)
}
fmt.Printf("%x %v\n", hash.Sum(nil), os.Args[2])
} else {
// If first arg doesn't match.
fmt.Printf("Requires Hashing Algorithm\n./hashfile sha1 /path/to/file\n")
}
} else {
fmt.Printf("Requires File Location\n./hashfile sha1 /path/to/file\n")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment