/
hash.go
executable file
·83 lines (74 loc) · 1.75 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
72
73
74
75
76
77
78
79
80
81
82
83
/*
Copyright (C) CESS. All rights reserved.
Copyright (C) Cumulus Encrypted Storage System. All rights reserved.
SPDX-License-Identifier: Apache-2.0
*/
package utils
import (
"crypto/md5"
"crypto/sha256"
"encoding/hex"
"errors"
"io"
"os"
)
// CalcPathSHA256 is used to calculate the sha256 value
// of a file with a given path.
func CalcPathSHA256(fpath string) (string, error) {
f, err := os.Open(fpath)
if err != nil {
return "", err
}
defer f.Close()
return CalcFileSHA256(f)
}
// CalcFileSHA256 is used to calculate the sha256 value
// of the file type.
func CalcFileSHA256(f *os.File) (string, error) {
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
}
// CalcSHA256 is used to calculate the sha256 value
// of the data.
func CalcSHA256(data []byte) (string, error) {
if len(data) <= 0 {
return "", errors.New("data is nil")
}
h := sha256.New()
_, err := h.Write(data)
if err != nil {
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
}
// CalcSHA256 is used to calculate the sha256 value
// of the data.
func CalcMD5(data string) ([]byte, error) {
if len(data) <= 0 {
return nil, errors.New("data is nil")
}
m := md5.Sum([]byte(data))
return m[:], nil
}
// CalcPathSHA256 is used to calculate the sha256 value
// of a file with a given path.
func CalcPathSHA256Bytes(fpath string) ([]byte, error) {
f, err := os.Open(fpath)
if err != nil {
return nil, err
}
defer f.Close()
return CalcFileSHA256Bytes(f)
}
// CalcFileSHA256 is used to calculate the sha256 value
// of the file type.
func CalcFileSHA256Bytes(f *os.File) ([]byte, error) {
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return nil, err
}
return h.Sum(nil), nil
}