-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
hash.go
71 lines (56 loc) · 1.26 KB
/
hash.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package filetrove
import (
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"errors"
"hash"
"io"
"os"
"golang.org/x/crypto/blake2b"
)
// HashSumsFile contains all hashes for a single file
type HashSumsFile struct {
MD5 []byte
SHA1 []byte
SHA256 []byte
SHA512 []byte
BLAKE2B512 []byte
}
// ReturnSupportedHashes returns a list of supported hashes
func ReturnSupportedHashes() [5]string {
return [5]string{"md5", "sha1", "sha256", "sha512", "blake2b-512"}
}
// Hashit hashes a file using the provided hash algorithm
func Hashit(inFile string, hashalg string) ([]byte, error) {
fd, err := os.Open(inFile)
if err != nil {
return []byte{}, err
}
defer fd.Close()
var hasher hash.Hash
if hashalg == "sha256" {
hasher = sha256.New()
} else if hashalg == "md5" {
hasher = md5.New()
} else if hashalg == "sha1" {
hasher = sha1.New()
} else if hashalg == "sha512" {
hasher = sha512.New()
} else if hashalg == "blake2b-512" {
hasher, err = blake2b.New512(nil)
if err != nil {
return []byte{}, err
}
} else {
return []byte{}, errors.New("Hash not implemented.")
}
_, err = io.Copy(hasher, fd)
if err != nil {
return []byte{}, err
}
io.Copy(hasher, fd)
checksum := hasher.Sum(nil)
return checksum, nil
}