Skip to content

Instantly share code, notes, and snippets.

@Zenithar
Last active November 29, 2015 19:39
Show Gist options
  • Save Zenithar/6daafdd0c02d69690ba7 to your computer and use it in GitHub Desktop.
Save Zenithar/6daafdd0c02d69690ba7 to your computer and use it in GitHub Desktop.
One read multiple hash
package main
import (
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"fmt"
"hash"
"hash/crc32"
"hash/crc64"
"io"
"log"
"math"
"os"
"github.com/codahale/blake2"
"github.com/jzelinskie/whirlpool"
"github.com/michielbuddingh/spamsum"
"golang.org/x/crypto/md4"
"golang.org/x/crypto/ripemd160"
"golang.org/x/crypto/sha3"
)
const (
spamSumLength = uint64(64)
minBlockSize = uint64(3)
)
var (
h = map[string]hash.Hash{}
fileChunk = minBlockSize
)
func main() {
// Open the file
fp, err := os.Open(os.Args[1])
if err != nil {
log.Fatal(err)
}
// close fp on exit and check for its returned error
defer func() {
if err := fp.Close(); err != nil {
panic(err)
}
}()
// Calculate chunk count
stat, _ := fp.Stat()
size := stat.Size()
// Determine best blocksize
for fileChunk*spamSumLength < uint64(size) {
fileChunk = fileChunk * 2
}
// Initialize hash map
h["crc32"] = crc32.NewIEEE()
h["crc64"] = crc64.New(crc64.MakeTable(crc64.ISO))
h["md4"] = md4.New()
h["md5"] = md5.New()
h["sha1"] = sha1.New()
h["whirlpool"] = whirlpool.New()
h["blake2b"] = blake2.NewBlake2B()
h["sha2-256"] = sha256.New()
h["sha2-512"] = sha512.New()
h["ripemd160"] = ripemd160.New()
h["sha3-256"] = sha3.New256()
h["sha3-384"] = sha3.New384()
h["sha3-512"] = sha3.New512()
h["ssdeep"] = spamsum.StartFixedBlocksize(uint32(fileChunk))
// Count file chunks
chunks := uint64(math.Ceil(float64(size) / float64(fileChunk)))
// Read file
for i := uint64(0); i < chunks; i++ {
csize := int(math.Min(float64(fileChunk), float64(uint64(size)-uint64(i*fileChunk))))
buf := make([]byte, csize)
_, err := fp.Read(buf)
if err != nil && err != io.EOF {
panic(err)
}
// Hash block
for _, hf := range h {
hf.Write(buf)
}
}
// Display hash
fmt.Printf("CRC32 : %x\n", h["crc32"].Sum(nil))
fmt.Printf("CRC64 : %x\n", h["crc64"].Sum(nil))
fmt.Printf("MD4 : %x\n", h["md4"].Sum(nil))
fmt.Printf("MD5 : %x\n", h["md5"].Sum(nil))
fmt.Printf("RIPEMD-160 : %x\n", h["ripemd160"].Sum(nil))
fmt.Printf("SHA-1 : %x\n", h["sha1"].Sum(nil))
fmt.Printf("SHA2-256 : %x\n", h["sha2-256"].Sum(nil))
fmt.Printf("SHA3-256 : %x\n", h["sha3-256"].Sum(nil))
fmt.Printf("SHA3-384 : %x\n", h["sha3-384"].Sum(nil))
fmt.Printf("SHA2-512 : %x\n", h["sha2-512"].Sum(nil))
fmt.Printf("SHA3-512 : %x\n", h["sha3-512"].Sum(nil))
fmt.Printf("WHIRLPOOL : %x\n", h["whirlpool"].Sum(nil))
fmt.Printf("BLAKE2B : %x\n", h["blake2b"].Sum(nil))
fmt.Printf("SSDEEP : %s\n", h["ssdeep"].(*spamsum.SpamSumWriter).String())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment