Last active
February 25, 2022 19:47
-
-
Save alimsk/9432633f6e3b3b933e5231f817371dae to your computer and use it in GitHub Desktop.
hash multiple files in Go
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 ( | |
"crypto/md5" | |
"crypto/sha1" | |
"crypto/sha256" | |
"crypto/sha512" | |
"encoding/hex" | |
"flag" | |
"fmt" | |
"log" | |
"os" | |
) | |
type Hasher func([]byte) ([]byte, int) | |
func (h Hasher) Size() int { | |
_, size := h(nil) | |
return size | |
} | |
func sha256Hasher(data []byte) ([]byte, int) { | |
sum := sha256.Sum256(data) | |
return sum[:], sha256.Size | |
} | |
func md5Hasher(data []byte) ([]byte, int) { | |
sum := md5.Sum(data) | |
return sum[:], md5.Size | |
} | |
func sha224Hasher(data []byte) ([]byte, int) { | |
sum := sha256.Sum224(data) | |
return sum[:], sha256.Size224 | |
} | |
func sha512Hasher(data []byte) ([]byte, int) { | |
sum := sha512.Sum512(data) | |
return sum[:], sha512.Size | |
} | |
func sha384Hasher(data []byte) ([]byte, int) { | |
sum := sha512.Sum384(data) | |
return sum[:], sha512.Size384 | |
} | |
func sha1Hasher(data []byte) ([]byte, int) { | |
sum := sha1.Sum(data) | |
return sum[:], sha1.Size | |
} | |
var algoMap = map[string]Hasher{ | |
"sha256": sha256Hasher, | |
"md5": md5Hasher, | |
"sha224": sha224Hasher, | |
"sha512": sha512Hasher, | |
"sha384": sha384Hasher, | |
"sha1": sha1Hasher, | |
} | |
var algo = flag.String("a", "sha256", ""+ | |
"hashing algorithm\n"+ | |
"available algorithms:\n"+ | |
" sha256\n"+ | |
" md5\n"+ | |
" sha224\n"+ | |
" sha512\n"+ | |
" sha384\n"+ | |
" sha1\n", | |
) | |
func main() { | |
flag.Parse() | |
log.SetFlags(0) | |
hasher, ok := algoMap[*algo] | |
if !ok { | |
log.Fatal("algorithm not available: ", *algo) | |
} | |
combined := make([]byte, hasher.Size()) | |
for _, input := range flag.Args() { | |
data, err := os.ReadFile(input) | |
if err != nil { | |
log.Fatal(err) | |
} | |
sum, _ := hasher(data) | |
for i, b := range sum { | |
combined[i] ^= b | |
} | |
} | |
fmt.Println(hex.EncodeToString(combined)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment