/
calc_hash.go
122 lines (100 loc) · 2.12 KB
/
calc_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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package hash
import (
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
)
// SumTexto devuelve el hash para un texto
func SumTexto(s string, algo string) []byte {
var sum []byte
switch algo {
case "md5":
h := md5.New()
h.Write([]byte(s))
sum = h.Sum(nil)
case "sha256":
h := sha256.New()
h.Write([]byte(s))
sum = h.Sum(nil)
default:
h := sha1.New()
h.Write([]byte(s))
sum = h.Sum(nil)
}
return sum
}
// SumArchivo devuelve el hash de un archivo
// utilizando el algoritmo especificado
func SumArchivo(a string, algo string) ([]byte, error) {
var sum []byte
f, err := os.Open(a)
if err != nil {
return sum, err
}
defer f.Close()
switch algo {
case "sha256":
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return sum, err
}
sum = h.Sum(nil)
case "sha1":
h := sha1.New()
if _, err := io.Copy(h, f); err != nil {
return sum, err
}
sum = h.Sum(nil)
case "md5":
h := md5.New()
if _, err := io.Copy(h, f); err != nil {
return sum, err
}
sum = h.Sum(nil)
}
return sum, err
}
// SumDirectorio imprime el hash para los archivos
// de un directorio, sin incluir los subdirectorios
func SumDirectorio(dir string, algo string) {
archivos, err := ioutil.ReadDir(dir)
if err != nil {
fmt.Printf("* Error: %s\n", err)
}
for _, f := range archivos {
if !f.IsDir() {
// Se usa la ruta completa para poder localizar el archivo
// al momento de calcular el hash
archivo := filepath.Join(dir, f.Name())
hash, err := SumArchivo(archivo, algo)
if err != nil {
fmt.Printf("* Error: %s\n", err)
} else {
fmt.Printf("%x *%s\n", hash, f.Name())
}
}
}
}
// SumRecursivo imprime el hash para los archivos de
// un directorio, incluyendo los subdirectorios
func SumRecursivo(dir string, algo string) {
filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
hash, err := SumArchivo(path, algo)
if err != nil {
fmt.Printf("* Error: %s\n", err)
} else {
fmt.Printf("%x *%s\n", hash, path)
}
}
return nil
})
}