@@ -19,6 +19,7 @@ import (
19
19
"fmt"
20
20
"hash"
21
21
"io"
22
+ "regexp"
22
23
)
23
24
24
25
// Algorithm identifies and implementation of a digester by an identifier.
@@ -28,9 +29,9 @@ type Algorithm string
28
29
29
30
// supported digest types
30
31
const (
31
- SHA256 Algorithm = "sha256" // sha256 with hex encoding
32
- SHA384 Algorithm = "sha384" // sha384 with hex encoding
33
- SHA512 Algorithm = "sha512" // sha512 with hex encoding
32
+ SHA256 Algorithm = "sha256" // sha256 with hex encoding (lower case only)
33
+ SHA384 Algorithm = "sha384" // sha384 with hex encoding (lower case only)
34
+ SHA512 Algorithm = "sha512" // sha512 with hex encoding (lower case only)
34
35
35
36
// Canonical is the primary digest algorithm used with the distribution
36
37
// project. Other digests may be used but this one is the primary storage
50
51
SHA384 : crypto .SHA384 ,
51
52
SHA512 : crypto .SHA512 ,
52
53
}
54
+
55
+ // anchoredEncodedRegexps contains anchored regular expressions for hex-encoded digests.
56
+ // Note that /A-F/ disallowed.
57
+ anchoredEncodedRegexps = map [Algorithm ]* regexp.Regexp {
58
+ SHA256 : regexp .MustCompile (`^[a-f0-9]{64}$` ),
59
+ SHA384 : regexp .MustCompile (`^[a-f0-9]{96}$` ),
60
+ SHA512 : regexp .MustCompile (`^[a-f0-9]{128}$` ),
61
+ }
53
62
)
54
63
55
64
// Available returns true if the digest type is available for use. If this
@@ -164,3 +173,20 @@ func (a Algorithm) FromBytes(p []byte) Digest {
164
173
func (a Algorithm ) FromString (s string ) Digest {
165
174
return a .FromBytes ([]byte (s ))
166
175
}
176
+
177
+ // Validate validates the encoded portion string
178
+ func (a Algorithm ) Validate (encoded string ) error {
179
+ r , ok := anchoredEncodedRegexps [a ]
180
+ if ! ok {
181
+ return ErrDigestUnsupported
182
+ }
183
+ // Digests much always be hex-encoded, ensuring that their hex portion will
184
+ // always be size*2
185
+ if a .Size ()* 2 != len (encoded ) {
186
+ return ErrDigestInvalidLength
187
+ }
188
+ if r .MatchString (encoded ) {
189
+ return nil
190
+ }
191
+ return ErrDigestInvalidFormat
192
+ }
0 commit comments