-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsri-gen.go
109 lines (90 loc) · 2.02 KB
/
sri-gen.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
package main
import (
"crypto/sha256"
"crypto/sha512"
"encoding/hex"
"flag"
"fmt"
"io/ioutil"
"os"
"strconv"
)
type sri struct {
fileName string
hashType int
hash string
}
func main() {
filePaths := os.Args[2:]
hashType := flag.Int("hash", 256, "Hashing algorithm to use (256/384/512)")
flag.Parse()
results := make(chan sri, len(filePaths))
var sriResults = make([]sri, len(filePaths))
hashFunction := hashChooser(hashType)
for _, filePath := range filePaths {
go func(filePath string) {
hash := generateHash(filePath, hashFunction)
resultData := sri{
fileName: filePath,
hash: hex.EncodeToString(hash),
hashType: *hashType}
results <- resultData
}(filePath)
}
for i := 0; i < len(filePaths); i++ {
sriResults[i] = <-results
}
writeToFile(sriResults)
}
func writeToFile(data []sri) {
file, err := os.Create("result.txt")
check(err)
defer file.Close()
fmt.Fprintf(file, "File\tHash\n\n")
for _, result := range data {
sriHash := "sha" + strconv.Itoa(result.hashType) + "-" + result.hash
line := fmt.Sprintf("%s\t%s\n", result.fileName, sriHash)
fmt.Fprintf(file, line)
}
fmt.Println("Finished creating file")
}
func generateHash(path string, hashFunction func(data string) []uint8) []uint8 {
fileContents := readFile(path)
return hashFunction(fileContents)
}
func hashChooser(hashType *int) func(data string) []uint8 {
switch *hashType {
case 256:
return create256Hash
case 384:
return create384Hash
case 512:
return create512Hash
}
return create256Hash
}
func readFile(path string) string {
content, err := ioutil.ReadFile(path)
check(err)
return string(content)
}
func create256Hash(data string) []uint8 {
hash := sha256.New()
hash.Write([]byte(data))
return hash.Sum(nil)
}
func create384Hash(data string) []uint8 {
hash := sha512.New384()
hash.Write([]byte(data))
return hash.Sum(nil)
}
func create512Hash(data string) []uint8 {
hash := sha512.New()
hash.Write([]byte(data))
return hash.Sum(nil)
}
func check(e error) {
if e != nil {
panic(e)
}
}