-
Notifications
You must be signed in to change notification settings - Fork 0
/
checksum.go
81 lines (69 loc) · 1.63 KB
/
checksum.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
72
73
74
75
76
77
78
79
80
81
package assets
import (
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"encoding/hex"
"errors"
)
// ChecksumAlgo enumerates checksum algorihms.
type ChecksumAlgo int
const (
// MD5 is the MD5 algorithm.
MD5 = iota
// SHA1 is the SHA1 algorithm.
SHA1
// SHA256 is the SHA256 algorithm.
SHA256
// SHA512 is the SHA512 algorithm.
SHA512
)
var (
// ErrChecksumMismatch is returned when the expected checksum differs from the calculated one
ErrChecksumMismatch = errors.New("checksum mismatch")
// ErrChecksumUnknown is returned when an invalid checksum algorithm is specified
ErrChecksumUnknown = errors.New("unknown checksum algorithm")
)
// Checksum describes a checksum verification for an asset source.
type Checksum struct {
Algo ChecksumAlgo
Value string
}
func verifyChecksum(chksum *Checksum, data []byte) error {
switch chksum.Algo {
case MD5:
return compare(chksum.Value, calcMD5(data))
case SHA1:
return compare(chksum.Value, calcSHA1(data))
case SHA256:
return compare(chksum.Value, calcSHA256(data))
case SHA512:
return compare(chksum.Value, calcSHA512(data))
default:
return ErrChecksumUnknown
}
}
func calcMD5(data []byte) []byte {
h := md5.New()
h.Write(data)
return h.Sum(nil)
}
func calcSHA1(data []byte) []byte {
checksum := sha1.Sum(data)
return checksum[:]
}
func calcSHA256(data []byte) []byte {
checksum := sha256.Sum256(data)
return checksum[:]
}
func calcSHA512(data []byte) []byte {
checksum := sha512.Sum512(data)
return checksum[:]
}
func compare(value string, checksum []byte) error {
if value != hex.EncodeToString(checksum[:]) {
return ErrChecksumMismatch
}
return nil
}