Created
June 11, 2011 00:30
-
-
Save mkmik/1020088 to your computer and use it in GitHub Desktop.
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 - 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" | |
"time" | |
) | |
type ParallelWriter struct { | |
writer io.Writer | |
ch chan []byte | |
} | |
func NewParallelWriter(writer io.Writer) ParallelWriter { | |
ch := make(chan []byte, 100) | |
go func() { | |
for chunk := range ch { | |
writer.Write(chunk) | |
} | |
}() | |
return ParallelWriter{writer, ch} | |
} | |
func (self ParallelWriter) Write(p []byte) (n int, err os.Error) { | |
cp := make([]byte, len(p), len(p)) | |
copy(cp, p) | |
self.ch <- cp | |
return len(p), nil | |
} | |
func main() { | |
parallel := flag.Bool("parallel", false, "enable parallel calculation of multiple hash algorithms") | |
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 { | |
if *parallel { | |
writers = append(writers, NewParallelWriter(impls[i])) | |
} else { | |
writers = append(writers, impls[i]) | |
} | |
} | |
} | |
dest := io.MultiWriter(writers...) | |
io.Copy(dest, infile) | |
if *parallel { | |
time.Sleep(2e9) | |
} | |
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