forked from paketo-buildpacks/packit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
validated_reader.go
92 lines (75 loc) · 1.56 KB
/
validated_reader.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
package cargo
import (
"bytes"
"crypto/sha256"
"crypto/sha512"
"encoding/hex"
"errors"
"fmt"
"hash"
"io"
)
var ChecksumValidationError = errors.New("validation error: checksum does not match")
type ValidatedReader struct {
reader io.Reader
checksum Checksum
hash hash.Hash
}
type errorHash struct {
hash.Hash
err error
}
func NewValidatedReader(reader io.Reader, sum string) ValidatedReader {
var hash hash.Hash
checksum := Checksum(sum)
switch checksum.Algorithm() {
case "sha256":
hash = sha256.New()
case "sha512":
hash = sha512.New()
default:
return ValidatedReader{hash: errorHash{err: fmt.Errorf("unsupported algorithm %q: the following algorithms are supported [sha256, sha512]", checksum.Algorithm())}}
}
return ValidatedReader{
reader: reader,
checksum: checksum,
hash: hash,
}
}
func (vr ValidatedReader) Read(p []byte) (int, error) {
if errHash, ok := vr.hash.(errorHash); ok {
return 0, errHash.err
}
var done bool
n, err := vr.reader.Read(p)
if err != nil {
if err == io.EOF {
done = true
} else {
return n, err
}
}
buffer := bytes.NewBuffer(p)
_, err = io.CopyN(vr.hash, buffer, int64(n))
if err != nil {
return n, err
}
if done {
sum := hex.EncodeToString(vr.hash.Sum(nil))
if sum != vr.checksum.Hash() {
return n, ChecksumValidationError
}
return n, io.EOF
}
return n, nil
}
func (vr ValidatedReader) Valid() (bool, error) {
_, err := io.Copy(io.Discard, vr)
if err != nil {
if err == ChecksumValidationError {
return false, nil
}
return false, err
}
return true, nil
}