-
Notifications
You must be signed in to change notification settings - Fork 147
/
shasum.go
51 lines (43 loc) · 1.08 KB
/
shasum.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
package utils
import (
"crypto/sha256"
"encoding/hex"
"io"
"os"
"github.com/sirupsen/logrus"
)
func ValidateSha256Sum(expectedChecksum string, path string) {
actualChecksum, _ := GetSha256Sum(path)
if expectedChecksum != actualChecksum {
logrus.WithFields(logrus.Fields{
"Source": path,
"Expected": expectedChecksum,
"Actual": actualChecksum,
}).Fatal("Invalid or mismatched file checksum")
}
}
// GetSha256Sum returns the computed SHA256 Sum of a given file
func GetSha256Sum(path string) (string, error) {
var data io.ReadCloser
var err error
if IsUrl(path) {
// Handle download from URL
logrus.Warn("This is a remote source. If a published checksum is available you should use that rather than calculating it directly from the remote link.")
data = Fetch(path)
} else {
// Handle local file
data, err = os.Open(path)
if err != nil {
return "", err
}
}
defer data.Close()
hash := sha256.New()
_, err = io.Copy(hash, data)
if err != nil {
return "", err
} else {
computedHash := hex.EncodeToString(hash.Sum(nil))
return computedHash, nil
}
}