verifiers.go 1014 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package digest
  2. import (
  3. "hash"
  4. "io"
  5. )
  6. // Verifier presents a general verification interface to be used with message
  7. // digests and other byte stream verifications. Users instantiate a Verifier
  8. // from one of the various methods, write the data under test to it then check
  9. // the result with the Verified method.
  10. type Verifier interface {
  11. io.Writer
  12. // Verified will return true if the content written to Verifier matches
  13. // the digest.
  14. Verified() bool
  15. }
  16. // NewDigestVerifier returns a verifier that compares the written bytes
  17. // against a passed in digest.
  18. func NewDigestVerifier(d Digest) (Verifier, error) {
  19. if err := d.Validate(); err != nil {
  20. return nil, err
  21. }
  22. return hashVerifier{
  23. hash: d.Algorithm().Hash(),
  24. digest: d,
  25. }, nil
  26. }
  27. type hashVerifier struct {
  28. digest Digest
  29. hash hash.Hash
  30. }
  31. func (hv hashVerifier) Write(p []byte) (n int, err error) {
  32. return hv.hash.Write(p)
  33. }
  34. func (hv hashVerifier) Verified() bool {
  35. return hv.digest == NewDigest(hv.digest.Algorithm(), hv.hash)
  36. }