...
1
16
17 package hash
18
19 import (
20 "crypto/sha1"
21 "crypto/sha256"
22 "crypto/sha512"
23 "encoding/hex"
24 "errors"
25 "fmt"
26 "hash"
27 "io"
28 "os"
29
30 "github.com/sirupsen/logrus"
31 )
32
33
34 func SHA512ForFile(filename string) (string, error) {
35 return ForFile(filename, sha512.New())
36 }
37
38
39 func SHA256ForFile(filename string) (string, error) {
40 return ForFile(filename, sha256.New())
41 }
42
43
44
45 func SHA1ForFile(filename string) (string, error) {
46 return ForFile(filename, sha1.New())
47 }
48
49
50 func ForFile(filename string, hasher hash.Hash) (string, error) {
51 if hasher == nil {
52 return "", errors.New("provided hasher is nil")
53 }
54
55 f, err := os.Open(filename)
56 if err != nil {
57 return "", fmt.Errorf("open file %s: %w", filename, err)
58 }
59 defer func() {
60 if err := f.Close(); err != nil {
61 logrus.Warnf("Unable to close file %q: %v", filename, err)
62 }
63 }()
64
65 hasher.Reset()
66 if _, err := io.Copy(hasher, f); err != nil {
67 return "", fmt.Errorf("hash file %s: %w", filename, err)
68 }
69
70 return hex.EncodeToString(hasher.Sum(nil)), nil
71 }
72
View as plain text