forked from christian-korneck/python-go
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchecksig.go
More file actions
87 lines (73 loc) · 1.77 KB
/
Copy pathchecksig.go
File metadata and controls
87 lines (73 loc) · 1.77 KB
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
package main
import (
"bufio"
"crypto/sha1"
"fmt"
"io"
"os"
"path"
"strings"
"golang.org/x/sync/errgroup"
)
// CheckSignatures calculates sha1 signatures for files in rootDir and compare
// them with signatures found at "sha1sum.txt" in the same directory. It'll
// return an error if one of the signatures don't match
func CheckSignatures(rootDir string) error {
file, err := os.Open(path.Join(rootDir, "sha1sum.txt"))
if err != nil {
return err
}
defer file.Close()
sigs, err := parseSigFile(file)
if err != nil {
return err
}
var g errgroup.Group
for name, signature := range sigs {
fileName := path.Join(rootDir, name)
expected := signature
g.Go(func() error {
sig, err := fileSig(fileName)
if err != nil {
return err
}
if sig != expected {
return fmt.Errorf("%q - mismatch", fileName)
}
return nil
})
}
return g.Wait()
}
// fileSig returns the fileName sha1 digital signature of the specified file.
func fileSig(fileName string) (string, error) {
file, err := os.Open(fileName)
if err != nil {
return "", err
}
defer file.Close()
hash := sha1.New()
if _, err = io.Copy(hash, file); err != nil {
return "", err
}
return fmt.Sprintf("%x", hash.Sum(nil)), nil
}
// parseSigFile parses the signature file and returns a map of path->signature.
func parseSigFile(r io.Reader) (map[string]string, error) {
sigs := make(map[string]string)
scanner := bufio.NewScanner(r)
lnum := 0
for scanner.Scan() {
lnum++
// Line example: 6c6427da7893932731901035edbb9214 nasa-00.log
fields := strings.Fields(scanner.Text())
if len(fields) != 2 {
return nil, fmt.Errorf("%d: bad line: %q", lnum, scanner.Text())
}
sigs[fields[1]] = fields[0]
}
if err := scanner.Err(); err != nil {
return nil, err
}
return sigs, nil
}