-
Notifications
You must be signed in to change notification settings - Fork 36
/
multiple_digest.go
253 lines (201 loc) · 5.78 KB
/
multiple_digest.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
package crypto
import (
"errors"
"fmt"
"io"
"strings"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
boshsys "github.com/cloudfoundry/bosh-utils/system"
"os"
"unicode"
)
type MultipleDigest struct {
digests []Digest
}
func MustNewMultipleDigest(digests ...Digest) MultipleDigest {
if len(digests) == 0 {
panic("no digests have been provided")
}
return MultipleDigest{digests}
}
func MustParseMultipleDigest(json string) MultipleDigest {
digest, err := ParseMultipleDigest(json)
if err != nil {
panic(fmt.Sprintf("Parsing multiple digest: %s", err))
}
return digest
}
func ParseMultipleDigest(json string) (MultipleDigest, error) {
var digest MultipleDigest
err := (&digest).UnmarshalJSON([]byte(json))
if err != nil {
return MultipleDigest{}, err
}
return digest, nil
}
func NewMultipleDigestFromPath(filePath string, fs boshsys.FileSystem, algos []Algorithm) (MultipleDigest, error) {
file, err := fs.OpenFile(filePath, os.O_RDONLY, 0)
if err != nil {
return MultipleDigest{}, bosherr.WrapErrorf(err, "Calculating digest of '%s'", filePath)
}
defer func() {
_ = file.Close()
}()
return NewMultipleDigest(file, algos)
}
func NewMultipleDigest(stream io.ReadSeeker, algos []Algorithm) (MultipleDigest, error) {
if len(algos) == 0 {
return MultipleDigest{}, errors.New("must provide at least one algorithm")
}
digests := []Digest{}
for _, algo := range algos {
stream.Seek(0, 0)
digest, err := algo.CreateDigest(stream)
if err != nil {
return MultipleDigest{}, err
}
digests = append(digests, digest)
}
return MultipleDigest{digests}, nil
}
func (m MultipleDigest) Algorithm() Algorithm { return m.strongestDigest().Algorithm() }
func (m MultipleDigest) String() string {
var result []string
for _, digest := range m.digests {
result = append(result, digest.String())
}
return strings.Join(result, ";")
}
func (m MultipleDigest) Verify(reader io.Reader) error {
err := m.validate()
if err != nil {
return err
}
return m.strongestDigest().Verify(reader)
}
func (m MultipleDigest) VerifyFilePath(filePath string, fs boshsys.FileSystem) error {
file, err := fs.OpenFile(filePath, os.O_RDONLY, 0)
if err != nil {
return bosherr.WrapErrorf(err, "Calculating digest of '%s'", filePath)
}
defer func() {
_ = file.Close()
}()
return m.Verify(file)
}
func (m MultipleDigest) validate() error {
if len(m.digests) == 0 {
return errors.New("Expected to find at least one digest")
}
algosUsed := map[string]struct{}{}
for _, digest := range m.digests {
algoName := digest.Algorithm().Name()
if _, found := algosUsed[algoName]; found {
return bosherr.Errorf("Multiple digests of the same algorithm '%s' found in digests '%s'", algoName, m.String())
}
algosUsed[algoName] = struct{}{}
}
return nil
}
func (m MultipleDigest) strongestDigest() Digest {
if len(m.digests) == 0 {
panic("no digests have been provided")
}
preferredAlgorithms := []Algorithm{DigestAlgorithmSHA512, DigestAlgorithmSHA256, DigestAlgorithmSHA1}
for _, algo := range preferredAlgorithms {
for _, digest := range m.digests {
if digest.Algorithm().Name() == algo.Name() {
return digest
}
}
}
return m.digests[0]
}
func (m *MultipleDigest) DigestFor(algo Algorithm) (Digest, error) {
for _, digest := range m.digests {
algoName := digest.Algorithm().Name()
if algoName == algo.Name() {
return digest, nil
}
}
return nil, errors.New("digest-for-algorithm-not-present")
}
func (m *MultipleDigest) UnmarshalJSON(data []byte) error {
digestString := strings.TrimSuffix(strings.TrimPrefix(string(data), `"`), `"`)
multiDigest, err := m.parseMultipleDigestString(digestString)
if err != nil {
return err
}
err = multiDigest.validate()
if err != nil {
return err
}
*m = multiDigest
return nil
}
func (m MultipleDigest) MarshalJSON() ([]byte, error) {
if len(m.digests) == 0 {
return nil, errors.New("no digests have been provided")
}
return []byte(fmt.Sprintf(`"%s"`, m.String())), nil
}
func (m MultipleDigest) parseMultipleDigestString(multipleDigest string) (MultipleDigest, error) {
pieces := strings.Split(multipleDigest, ";")
digests := []Digest{}
for _, digest := range pieces {
parsedDigest, err := m.parseDigestString(digest)
if err == nil {
digests = append(digests, parsedDigest)
} else if _, ok := err.(emptyDigestError); !ok {
return MultipleDigest{}, err
}
}
if len(digests) == 0 {
return MultipleDigest{}, errors.New("No digest algorithm found. Supported algorithms: sha1, sha256, sha512")
}
return MultipleDigest{digests: digests}, nil
}
type emptyDigestError struct{}
func (e emptyDigestError) Error() string {
return "Empty digest parsed from digest string"
}
func (MultipleDigest) parseDigestString(digest string) (Digest, error) {
if len(digest) == 0 {
return nil, emptyDigestError{}
}
pieces := strings.SplitN(digest, ":", 2)
for _, piece := range pieces {
if !isStringAlphanumeric(piece) {
return nil, errors.New("Unable to parse digest string. Digest and algorithm key can only contain alpha-numeric characters.")
}
}
if len(pieces) == 1 {
// historically digests were only sha1 and did not include a prefix.
// continue to support that behavior.
pieces = []string{"sha1", pieces[0]}
}
switch pieces[0] {
case "sha1":
return NewDigest(DigestAlgorithmSHA1, pieces[1]), nil
case "sha256":
return NewDigest(DigestAlgorithmSHA256, pieces[1]), nil
case "sha512":
return NewDigest(DigestAlgorithmSHA512, pieces[1]), nil
default:
return NewDigest(NewUnknownAlgorithm(pieces[0]), pieces[1]), nil
}
}
func isStringAlphanumeric(s string) bool {
if len(s) == 0 {
return false
}
for _, runes := range s {
if !isAlphanumeric(runes) {
return false
}
}
return true
}
func isAlphanumeric(r rune) bool {
return (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || unicode.IsDigit(r)
}