Created
July 11, 2018 18:05
-
-
Save daniel-woods/dd3a2ce2fb8047dccf3f9348bb2f65ea to your computer and use it in GitHub Desktop.
File Checksums in Go
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
| // ./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