-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathchecksum.go
56 lines (46 loc) · 991 Bytes
/
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
package go_bagit
import (
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"fmt"
"hash"
"io"
"os"
)
func ValidateChecksum(f *os.File, algorithm string, checksum string) error {
calculatedChecksum, err := GenerateChecksum(f, algorithm)
if err != nil {
return err
}
if calculatedChecksum != checksum {
return fmt.Errorf("%s validation failed: expected=\"%s\" found=\"%s\"", algorithm, checksum, calculatedChecksum)
}
return nil
}
func GenerateChecksum(f *os.File, algorithm string) (string, error) {
h := getHash(algorithm)
if h == nil {
return "", fmt.Errorf("%s is not a supported alogorithm", algorithm)
}
if _, err := io.Copy(h, f); err != nil {
return "", err
}
return fmt.Sprintf("%x", h.Sum(nil)), nil
}
func getHash(code string) hash.Hash {
if code == "md5" {
return md5.New()
}
if code == "sha1" {
return sha1.New()
}
if code == "sha256" {
return sha256.New()
}
if code == "sha512" {
return sha512.New()
}
return nil
}