-
Notifications
You must be signed in to change notification settings - Fork 0
/
md5.go
61 lines (52 loc) · 1.04 KB
/
md5.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
package crypto
import (
"bufio"
"crypto/md5"
"fmt"
"io"
"os"
)
/*
File name : md5.go
Author : miaoyc
Create date : 2021/12/2 4:34 下午
Description : md5 hash
*/
var (
readFileBufferSize = 65536
)
// Md5 md5加密,
// @data input: 需加密的字符串
// @return:加密之后的32个字符的数据
func Md5(data string) (md5str string) {
h := md5.New()
h.Write([]byte(data))
md5str = fmt.Sprintf("%x", h.Sum(nil))
return md5str
}
// MD5sumFromFile 计算文件的md5
func MD5sumFromFile(filename string) (string, error) {
if info, err := os.Stat(filename); err != nil {
return "", err
} else if info.IsDir() {
return "", nil
}
file, err := os.Open(filename)
if err != nil {
return "", err
}
defer file.Close()
hash := md5.New()
for buf, reader := make([]byte, readFileBufferSize), bufio.NewReader(file); ; {
n, err := reader.Read(buf)
if err != nil {
if err == io.EOF {
break
}
return "", err
}
hash.Write(buf[:n])
}
checksum := fmt.Sprintf("%x", hash.Sum(nil))
return checksum, nil
}