Improve labeled hash helpers

This commit is contained in:
Daniel 2022-09-28 14:45:01 +02:00
parent 7566eefcd7
commit 0fdd07b0e2
2 changed files with 34 additions and 12 deletions

View file

@ -175,16 +175,38 @@ func (lh *LabeledHash) EqualRaw(otherDigest []byte) bool {
return subtle.ConstantTimeCompare(lh.digest, otherDigest) == 1
}
// MatchesString returns true if the digest of the given string matches the hash.
func (lh *LabeledHash) MatchesString(s string) bool {
return lh.MatchesData([]byte(s))
// Matches returns true if the digest of the given data matches the hash.
func (lh *LabeledHash) Matches(data []byte) bool {
return lh.Equal(Digest(lh.alg, data))
}
// MatchesData returns true if the digest of the given data matches the hash.
// DEPRECATED: Use Matches instead.
func (lh *LabeledHash) MatchesData(data []byte) bool {
hasher := lh.alg.new()
_, _ = hasher.Write(data) // never returns an error
defer hasher.Reset() // internal state may leak data if kept in memory
return subtle.ConstantTimeCompare(lh.digest, hasher.Sum(nil)) == 1
return lh.Equal(Digest(lh.alg, data))
}
// MatchesString returns true if the digest of the given string matches the hash.
func (lh *LabeledHash) MatchesString(s string) bool {
return lh.Matches([]byte(s))
}
// MatchesFile returns true if the digest of the given file matches the hash.
func (lh *LabeledHash) MatchesFile(pathToFile string) (bool, error) {
fileHash, err := DigestFile(lh.alg, pathToFile)
if err != nil {
return false, err
}
return lh.Equal(fileHash), nil
}
// MatchesReader returns true if the digest of the given reader matches the hash.
func (lh *LabeledHash) MatchesReader(reader io.Reader) (bool, error) {
readerHash, err := DigestFromReader(lh.alg, reader)
if err != nil {
return false, err
}
return lh.Equal(readerHash), nil
}

View file

@ -42,13 +42,13 @@ func testAlgorithm(t *testing.T, alg Algorithm, emptyHex, foxHex string) {
}
// test matching with serialized/loaded labeled hash
if !lh.MatchesData(testFoxData) {
if !lh.Matches(testFoxData) {
t.Errorf("alg %d: failed to match reference", alg)
}
if !lh.MatchesString(testFox) {
t.Errorf("alg %d: failed to match reference", alg)
}
if lh.MatchesData(noMatchData) {
if lh.Matches(noMatchData) {
t.Errorf("alg %d: failed to non-match garbage", alg)
}
if lh.MatchesString(noMatch) {
@ -99,13 +99,13 @@ func testFormat(t *testing.T, alg Algorithm, lhs, loaded *LabeledHash) {
}
// Test matching.
if !loaded.MatchesData(testFoxData) {
if !loaded.Matches(testFoxData) {
t.Errorf("alg %d: failed to match reference", alg)
}
if !loaded.MatchesString(testFox) {
t.Errorf("alg %d: failed to match reference", alg)
}
if loaded.MatchesData(noMatchData) {
if loaded.Matches(noMatchData) {
t.Errorf("alg %d: failed to non-match garbage", alg)
}
if loaded.MatchesString(noMatch) {