Skip to content

Instantly share code, notes, and snippets.

@timsonner
Created May 28, 2023 17:29
Show Gist options
  • Select an option

  • Save timsonner/aa870d3e38db138ced444924a888d76b to your computer and use it in GitHub Desktop.

Select an option

Save timsonner/aa870d3e38db138ced444924a888d76b to your computer and use it in GitHub Desktop.
GoLang. Checks the hash of a file against an expected hash.
package main
import (
"crypto/md5"
"crypto/sha256"
"encoding/hex"
"flag"
"fmt"
"hash"
"io"
"log"
"os"
"strings"
)
func main() {
// Parse command-line arguments
filename := flag.String("filename", "", "Name of the file to check")
algorithm := flag.String("algorithm", "", "Hashing algorithm (sha256 or md5)")
expectedHash := flag.String("expected", "", "Expected hash value")
flag.Parse()
// Validate command-line arguments
if *filename == "" || *algorithm == "" || *expectedHash == "" {
flag.Usage()
os.Exit(1)
}
// Open the file
file, err := os.Open(*filename)
if err != nil {
log.Fatal(err)
}
defer file.Close()
// Create hasher
var hasher hash.Hash
// Normalize and validate command line argument -algorithm
switch strings.ToLower(*algorithm) {
case "sha256":
hasher = sha256.New()
case "md5":
hasher = md5.New()
default:
log.Fatalf("Unsupported algorithm: %s", *algorithm)
}
// Copy the contents of the file into the hasher
if _, err := io.Copy(hasher, file); err != nil {
log.Fatal(err)
}
// Get the computed hash of the file
computedHash := hex.EncodeToString(hasher.Sum(nil))
// Compare the computed hash of the file to the expected hash
if computedHash == *expectedHash {
fmt.Println("Hashes match!")
} else {
fmt.Println("Hashes do not match!")
fmt.Printf("Expected: %s\n", *expectedHash)
fmt.Printf("Computed: %s\n", computedHash)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment