Skip to content

Instantly share code, notes, and snippets.

@mkmik
Created June 10, 2011 23:03
Show Gist options
  • Save mkmik/1019970 to your computer and use it in GitHub Desktop.
Save mkmik/1019970 to your computer and use it in GitHub Desktop.
/*
Hash - Guillermo Estrada
Simple utility to obtain the MD5 and/or SHA-1
of a file from the command line.
2011
Edited: Marko Mikulicic 2011
*/
package main
import (
"io"
"os"
"fmt"
"flag"
"hash"
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"crypto/ripemd160"
)
func main() {
algos := [...]string{"md5", "sha1", "sha256", "sha512", "ripemd160"}
impls := [...]hash.Hash{md5.New(), sha1.New(), sha256.New(), sha512.New(), ripemd160.New()}
flags := make([]*bool, len(algos))
for i, a := range algos {
flags[i] = flag.Bool(a, false, fmt.Sprintf("-%s calculate %s hash of file", a, a))
}
flag.Parse()
any := false
for _, f := range flags {
any = any || *f
}
if any == false {
fmt.Println("err: No hash specified. Please run with --help to see list of supported hash algos")
os.Exit(1)
}
infile, err := os.Open(flag.Arg(0))
if err != nil {
fmt.Println(err)
os.Exit(1)
}
writers := make([]io.Writer, 0, len(impls))
for i, flag := range flags {
if *flag {
writers = append(writers, impls[i])
}
}
dest := io.MultiWriter(writers...)
io.Copy(dest, infile)
for i, flag := range flags {
if *flag {
fmt.Printf("%s: %x\n", algos[i], impls[i].Sum())
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment