Created
November 16, 2019 16:10
-
-
Save crissilvaeng/48b6f1eb86013cb82d04664ddcd65a40 to your computer and use it in GitHub Desktop.
CLI: echo "checksum *filename" | sha256sum -c -, but in Golang
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 | |
import ( | |
"io" | |
"os" | |
"log" | |
"fmt" | |
"flag" | |
"crypto/sha256" | |
"encoding/hex" | |
) | |
var hash, file string | |
func init () { | |
flag.StringVar(&hash, "hash", "", "sha256 sum") | |
flag.StringVar(&file, "file", "", "targer file") | |
} | |
func main() { | |
flag.Parse() | |
if len(hash) == 0 || len(file) == 0 { | |
flag.PrintDefaults() | |
os.Exit(2) | |
} | |
h, err := checksum(file) | |
if err != nil { | |
log.Fatal(err) | |
os.Exit(1) | |
} | |
if hash != h { | |
fmt.Println("error: checksum verification failed") | |
os.Exit(1) | |
} | |
fmt.Println("OK!") | |
} | |
func checksum(filename string) (string, error) { | |
f, err := os.Open(filename) | |
if err != nil { | |
return "", err | |
} | |
defer f.Close() | |
h := sha256.New() | |
if _, err := io.Copy(h, f); err != nil { | |
return "", err | |
} | |
hash := h.Sum(nil) | |
return hex.EncodeToString(hash), nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment