algorithm.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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. "crypto"
  17. "fmt"
  18. "hash"
  19. "io"
  20. )
  21. // Algorithm identifies and implementation of a digester by an identifier.
  22. // Note the that this defines both the hash algorithm used and the string
  23. // encoding.
  24. type Algorithm string
  25. // supported digest types
  26. const (
  27. SHA256 Algorithm = "sha256" // sha256 with hex encoding
  28. SHA384 Algorithm = "sha384" // sha384 with hex encoding
  29. SHA512 Algorithm = "sha512" // sha512 with hex encoding
  30. // Canonical is the primary digest algorithm used with the distribution
  31. // project. Other digests may be used but this one is the primary storage
  32. // digest.
  33. Canonical = SHA256
  34. )
  35. var (
  36. // TODO(stevvooe): Follow the pattern of the standard crypto package for
  37. // registration of digests. Effectively, we are a registerable set and
  38. // common symbol access.
  39. // algorithms maps values to hash.Hash implementations. Other algorithms
  40. // may be available but they cannot be calculated by the digest package.
  41. algorithms = map[Algorithm]crypto.Hash{
  42. SHA256: crypto.SHA256,
  43. SHA384: crypto.SHA384,
  44. SHA512: crypto.SHA512,
  45. }
  46. )
  47. // Available returns true if the digest type is available for use. If this
  48. // returns false, Digester and Hash will return nil.
  49. func (a Algorithm) Available() bool {
  50. h, ok := algorithms[a]
  51. if !ok {
  52. return false
  53. }
  54. // check availability of the hash, as well
  55. return h.Available()
  56. }
  57. func (a Algorithm) String() string {
  58. return string(a)
  59. }
  60. // Size returns number of bytes returned by the hash.
  61. func (a Algorithm) Size() int {
  62. h, ok := algorithms[a]
  63. if !ok {
  64. return 0
  65. }
  66. return h.Size()
  67. }
  68. // Set implemented to allow use of Algorithm as a command line flag.
  69. func (a *Algorithm) Set(value string) error {
  70. if value == "" {
  71. *a = Canonical
  72. } else {
  73. // just do a type conversion, support is queried with Available.
  74. *a = Algorithm(value)
  75. }
  76. if !a.Available() {
  77. return ErrDigestUnsupported
  78. }
  79. return nil
  80. }
  81. // Digester returns a new digester for the specified algorithm. If the algorithm
  82. // does not have a digester implementation, nil will be returned. This can be
  83. // checked by calling Available before calling Digester.
  84. func (a Algorithm) Digester() Digester {
  85. return &digester{
  86. alg: a,
  87. hash: a.Hash(),
  88. }
  89. }
  90. // Hash returns a new hash as used by the algorithm. If not available, the
  91. // method will panic. Check Algorithm.Available() before calling.
  92. func (a Algorithm) Hash() hash.Hash {
  93. if !a.Available() {
  94. // Empty algorithm string is invalid
  95. if a == "" {
  96. panic(fmt.Sprintf("empty digest algorithm, validate before calling Algorithm.Hash()"))
  97. }
  98. // NOTE(stevvooe): A missing hash is usually a programming error that
  99. // must be resolved at compile time. We don't import in the digest
  100. // package to allow users to choose their hash implementation (such as
  101. // when using stevvooe/resumable or a hardware accelerated package).
  102. //
  103. // Applications that may want to resolve the hash at runtime should
  104. // call Algorithm.Available before call Algorithm.Hash().
  105. panic(fmt.Sprintf("%v not available (make sure it is imported)", a))
  106. }
  107. return algorithms[a].New()
  108. }
  109. // Encode encodes the raw bytes of a digest, typically from a hash.Hash, into
  110. // the encoded portion of the digest.
  111. func (a Algorithm) Encode(d []byte) string {
  112. // TODO(stevvooe): Currently, all algorithms use a hex encoding. When we
  113. // add support for back registration, we can modify this accordingly.
  114. return fmt.Sprintf("%x", d)
  115. }
  116. // FromReader returns the digest of the reader using the algorithm.
  117. func (a Algorithm) FromReader(rd io.Reader) (Digest, error) {
  118. digester := a.Digester()
  119. if _, err := io.Copy(digester.Hash(), rd); err != nil {
  120. return "", err
  121. }
  122. return digester.Digest(), nil
  123. }
  124. // FromBytes digests the input and returns a Digest.
  125. func (a Algorithm) FromBytes(p []byte) Digest {
  126. digester := a.Digester()
  127. if _, err := digester.Hash().Write(p); err != nil {
  128. // Writes to a Hash should never fail. None of the existing
  129. // hash implementations in the stdlib or hashes vendored
  130. // here can return errors from Write. Having a panic in this
  131. // condition instead of having FromBytes return an error value
  132. // avoids unnecessary error handling paths in all callers.
  133. panic("write to hash function returned error: " + err.Error())
  134. }
  135. return digester.Digest()
  136. }
  137. // FromString digests the string input and returns a Digest.
  138. func (a Algorithm) FromString(s string) Digest {
  139. return a.FromBytes([]byte(s))
  140. }