2015-12-08 10:18:42 -08:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2016-01-03 20:15:32 -08:00
|
|
|
"crypto/md5"
|
2015-12-08 10:18:42 -08:00
|
|
|
"crypto/sha1"
|
|
|
|
"crypto/sha256"
|
|
|
|
"crypto/sha512"
|
|
|
|
"flag"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"os"
|
|
|
|
)
|
|
|
|
|
2015-12-10 14:46:06 -08:00
|
|
|
var algo = flag.String("a", "sha1", "algorithm to use")
|
2016-11-15 20:24:15 -08:00
|
|
|
var mode = flag.Bool("c", false, "check")
|
2015-12-08 10:18:42 -08:00
|
|
|
|
|
|
|
func main() {
|
|
|
|
flag.Parse()
|
|
|
|
files := flag.Args()
|
2016-11-15 20:24:15 -08:00
|
|
|
switch *mode {
|
|
|
|
case true:
|
|
|
|
if err := check(files); err != nil {
|
|
|
|
fmt.Fprintf(os.Stderr, "%v\n", err)
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
case false:
|
|
|
|
if err := hsh(files); err != nil {
|
|
|
|
fmt.Fprintf(os.Stderr, "%v\n", err)
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func hsh(files []string) error {
|
2015-12-08 10:18:42 -08:00
|
|
|
h := sha256.New()
|
|
|
|
switch *algo {
|
|
|
|
case "sha1", "1":
|
|
|
|
h = sha1.New()
|
|
|
|
case "sha256", "256":
|
|
|
|
h = sha256.New()
|
|
|
|
case "sha512", "512":
|
|
|
|
h = sha512.New()
|
2016-01-03 20:15:32 -08:00
|
|
|
case "md5":
|
|
|
|
h = md5.New()
|
2015-12-08 10:18:42 -08:00
|
|
|
default:
|
2016-11-15 20:24:15 -08:00
|
|
|
return fmt.Errorf("unsupported algorithm: %v", *algo)
|
2015-12-08 10:18:42 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
if len(files) == 0 {
|
|
|
|
_, err := io.Copy(h, os.Stdin)
|
|
|
|
if err != nil {
|
|
|
|
fmt.Fprintf(os.Stderr, "%v\n", err)
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
fmt.Printf("%x -\n", h.Sum(nil))
|
|
|
|
} else {
|
|
|
|
for _, name := range files {
|
|
|
|
f, err := os.Open(name)
|
|
|
|
if err != nil {
|
|
|
|
fmt.Fprintf(os.Stderr, "%v\n", err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
h.Reset()
|
|
|
|
_, err = io.Copy(h, f)
|
|
|
|
f.Close()
|
|
|
|
if err != nil {
|
|
|
|
fmt.Fprintf(os.Stderr, "%v\n", err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
fmt.Printf("%x %s\n", h.Sum(nil), name)
|
|
|
|
}
|
|
|
|
}
|
2016-11-15 20:24:15 -08:00
|
|
|
return nil
|
2015-12-08 10:18:42 -08:00
|
|
|
}
|