forked from aptly-dev/aptly
-
Notifications
You must be signed in to change notification settings - Fork 0
/
checksum.go
76 lines (62 loc) · 1.52 KB
/
checksum.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
package utils
import (
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"fmt"
"hash"
"io"
"os"
)
// ChecksumInfo represents checksums for a single file
type ChecksumInfo struct {
Size int64
MD5 string
SHA1 string
SHA256 string
}
// ChecksumsForFile generates size, MD5, SHA1 & SHA256 checksums for given file
func ChecksumsForFile(path string) (ChecksumInfo, error) {
file, err := os.Open(path)
if err != nil {
return ChecksumInfo{}, err
}
defer file.Close()
w := NewChecksumWriter()
_, err = io.Copy(w, file)
if err != nil {
return ChecksumInfo{}, err
}
return w.Sum(), nil
}
// ChecksumWriter is a writer that does checksum calculation on the fly passing data
// to real writer
type ChecksumWriter struct {
sum ChecksumInfo
hashes []hash.Hash
}
// Interface check
var (
_ io.Writer = &ChecksumWriter{}
)
// NewChecksumWriter creates checksum calculator for given writer w
func NewChecksumWriter() *ChecksumWriter {
return &ChecksumWriter{
hashes: []hash.Hash{md5.New(), sha1.New(), sha256.New()},
}
}
// Write implememnts pass-through writing with checksum calculation on the fly
func (c *ChecksumWriter) Write(p []byte) (n int, err error) {
c.sum.Size += int64(len(p))
for _, h := range c.hashes {
h.Write(p)
}
return len(p), nil
}
// Sum returns caculated ChecksumInfo
func (c *ChecksumWriter) Sum() ChecksumInfo {
c.sum.MD5 = fmt.Sprintf("%x", c.hashes[0].Sum(nil))
c.sum.SHA1 = fmt.Sprintf("%x", c.hashes[1].Sum(nil))
c.sum.SHA256 = fmt.Sprintf("%x", c.hashes[2].Sum(nil))
return c.sum
}