/
hasher.go
95 lines (80 loc) · 1.6 KB
/
hasher.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
84
85
86
87
88
89
90
91
92
93
94
95
package hash
import (
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"fmt"
"github.com/Mikubill/transfer/utils"
"hash/crc32"
"io"
"os"
"path/filepath"
"strconv"
)
func Hash(v []string) {
for _, item := range v {
if utils.IsExist(item) && !utils.IsDir(item) {
hash(item)
}
}
}
func hash(file string) {
stat, _ := os.Stat(file)
path, _ := filepath.Abs(file)
fmt.Println("size: " + strconv.FormatInt(stat.Size(), 10))
fmt.Println("path: " + path)
fmt.Println("")
fmt.Println("crc32: " + c32(file))
fmt.Println("md5: " + m5(file))
fmt.Println("sha1: " + s1(file))
fmt.Println("sha256: " + s256(file))
}
func s1(file string) string {
f, err := os.Open(file)
if err != nil {
return err.Error()
}
h := sha1.New()
if _, err := io.Copy(h, f); err != nil {
return err.Error()
}
_ = f.Close()
return fmt.Sprintf("%x", h.Sum(nil))
}
func c32(file string) string {
f, err := os.Open(file)
if err != nil {
return err.Error()
}
tablePolynomial := crc32.MakeTable(0xedb88320)
h := crc32.New(tablePolynomial)
if _, err := io.Copy(h, f); err != nil {
return err.Error()
}
_ = f.Close()
return fmt.Sprintf("%x", h.Sum(nil))
}
func m5(file string) string {
f, err := os.Open(file)
if err != nil {
return err.Error()
}
h := md5.New()
if _, err := io.Copy(h, f); err != nil {
return err.Error()
}
_ = f.Close()
return fmt.Sprintf("%x", h.Sum(nil))
}
func s256(file string) string {
f, err := os.Open(file)
if err != nil {
return err.Error()
}
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return err.Error()
}
_ = f.Close()
return fmt.Sprintf("%x", h.Sum(nil))
}