digest.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. // Copyright 2017 Docker, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package digest
  15. import (
  16. "fmt"
  17. "hash"
  18. "io"
  19. "regexp"
  20. "strings"
  21. )
  22. // Digest allows simple protection of hex formatted digest strings, prefixed
  23. // by their algorithm. Strings of type Digest have some guarantee of being in
  24. // the correct format and it provides quick access to the components of a
  25. // digest string.
  26. //
  27. // The following is an example of the contents of Digest types:
  28. //
  29. // sha256:7173b809ca12ec5dee4506cd86be934c4596dd234ee82c0662eac04a8c2c71dc
  30. //
  31. // This allows to abstract the digest behind this type and work only in those
  32. // terms.
  33. type Digest string
  34. // NewDigest returns a Digest from alg and a hash.Hash object.
  35. func NewDigest(alg Algorithm, h hash.Hash) Digest {
  36. return NewDigestFromBytes(alg, h.Sum(nil))
  37. }
  38. // NewDigestFromBytes returns a new digest from the byte contents of p.
  39. // Typically, this can come from hash.Hash.Sum(...) or xxx.SumXXX(...)
  40. // functions. This is also useful for rebuilding digests from binary
  41. // serializations.
  42. func NewDigestFromBytes(alg Algorithm, p []byte) Digest {
  43. return NewDigestFromEncoded(alg, alg.Encode(p))
  44. }
  45. // NewDigestFromHex is deprecated. Please use NewDigestFromEncoded.
  46. func NewDigestFromHex(alg, hex string) Digest {
  47. return NewDigestFromEncoded(Algorithm(alg), hex)
  48. }
  49. // NewDigestFromEncoded returns a Digest from alg and the encoded digest.
  50. func NewDigestFromEncoded(alg Algorithm, encoded string) Digest {
  51. return Digest(fmt.Sprintf("%s:%s", alg, encoded))
  52. }
  53. // DigestRegexp matches valid digest types.
  54. var DigestRegexp = regexp.MustCompile(`[a-z0-9]+(?:[.+_-][a-z0-9]+)*:[a-zA-Z0-9=_-]+`)
  55. // DigestRegexpAnchored matches valid digest types, anchored to the start and end of the match.
  56. var DigestRegexpAnchored = regexp.MustCompile(`^` + DigestRegexp.String() + `$`)
  57. var (
  58. // ErrDigestInvalidFormat returned when digest format invalid.
  59. ErrDigestInvalidFormat = fmt.Errorf("invalid checksum digest format")
  60. // ErrDigestInvalidLength returned when digest has invalid length.
  61. ErrDigestInvalidLength = fmt.Errorf("invalid checksum digest length")
  62. // ErrDigestUnsupported returned when the digest algorithm is unsupported.
  63. ErrDigestUnsupported = fmt.Errorf("unsupported digest algorithm")
  64. )
  65. // Parse parses s and returns the validated digest object. An error will
  66. // be returned if the format is invalid.
  67. func Parse(s string) (Digest, error) {
  68. d := Digest(s)
  69. return d, d.Validate()
  70. }
  71. // FromReader consumes the content of rd until io.EOF, returning canonical digest.
  72. func FromReader(rd io.Reader) (Digest, error) {
  73. return Canonical.FromReader(rd)
  74. }
  75. // FromBytes digests the input and returns a Digest.
  76. func FromBytes(p []byte) Digest {
  77. return Canonical.FromBytes(p)
  78. }
  79. // FromString digests the input and returns a Digest.
  80. func FromString(s string) Digest {
  81. return Canonical.FromString(s)
  82. }
  83. // Validate checks that the contents of d is a valid digest, returning an
  84. // error if not.
  85. func (d Digest) Validate() error {
  86. s := string(d)
  87. i := strings.Index(s, ":")
  88. if i <= 0 || i+1 == len(s) {
  89. return ErrDigestInvalidFormat
  90. }
  91. algorithm, encoded := Algorithm(s[:i]), s[i+1:]
  92. if !algorithm.Available() {
  93. if !DigestRegexpAnchored.MatchString(s) {
  94. return ErrDigestInvalidFormat
  95. }
  96. return ErrDigestUnsupported
  97. }
  98. return algorithm.Validate(encoded)
  99. }
  100. // Algorithm returns the algorithm portion of the digest. This will panic if
  101. // the underlying digest is not in a valid format.
  102. func (d Digest) Algorithm() Algorithm {
  103. return Algorithm(d[:d.sepIndex()])
  104. }
  105. // Verifier returns a writer object that can be used to verify a stream of
  106. // content against the digest. If the digest is invalid, the method will panic.
  107. func (d Digest) Verifier() Verifier {
  108. return hashVerifier{
  109. hash: d.Algorithm().Hash(),
  110. digest: d,
  111. }
  112. }
  113. // Encoded returns the encoded portion of the digest. This will panic if the
  114. // underlying digest is not in a valid format.
  115. func (d Digest) Encoded() string {
  116. return string(d[d.sepIndex()+1:])
  117. }
  118. // Hex is deprecated. Please use Digest.Encoded.
  119. func (d Digest) Hex() string {
  120. return d.Encoded()
  121. }
  122. func (d Digest) String() string {
  123. return string(d)
  124. }
  125. func (d Digest) sepIndex() int {
  126. i := strings.Index(string(d), ":")
  127. if i < 0 {
  128. panic(fmt.Sprintf("no ':' separator in digest %q", d))
  129. }
  130. return i
  131. }