ahash: add SumLimitedReader

This commit is contained in:
Kyle Isom 2023-05-04 13:41:33 -07:00
parent 90318f861b
commit 078230217d
2 changed files with 29 additions and 1 deletions

View File

@ -1,4 +1,5 @@
// Package ahash provides support for hashing data with a selectable // Package ahash provides support for hashing data with a selectable
//
// hash function. // hash function.
package ahash package ahash
@ -213,6 +214,17 @@ func SumReader(algo string, r io.Reader) ([]byte, error) {
return h.Sum(nil), nil return h.Sum(nil), nil
} }
// SumLimitedReader reads n bytes of data from the io.reader and returns the
// digest (not the hex digest) from the specified algorithm.
func SumLimitedReader(algo string, r io.Reader, n int64) ([]byte, error) {
limit := &io.LimitedReader{
R: r,
N: n,
}
return SumReader(algo, limit)
}
var insecureHashList, secureHashList, hashList []string var insecureHashList, secureHashList, hashList []string
func init() { func init() {

View File

@ -139,3 +139,19 @@ func TestListLengthSanity(t *testing.T) {
assert.BoolT(t, len(all) == len(secure)+len(insecure)) assert.BoolT(t, len(all) == len(secure)+len(insecure))
} }
func TestSumLimitedReader(t *testing.T) {
data := bytes.NewBufferString("hello, world")
dataLen := data.Len()
extendedData := bytes.NewBufferString("hello, world! this is an extended message")
expected := "09ca7e4eaa6e8ae9c7d261167129184883644d07dfba7cbfbc4c8a2e08360d5b"
hash, err := SumReader("sha256", data)
assert.NoErrorT(t, err)
assert.BoolT(t, fmt.Sprintf("%x", hash) == expected, fmt.Sprintf("have hash %x, want %s", hash, expected))
extendedHash, err := SumLimitedReader("sha256", extendedData, int64(dataLen))
assert.NoErrorT(t, err)
assert.BoolT(t, bytes.Equal(hash, extendedHash), fmt.Sprintf("have hash %x, want %x", extendedHash, hash))
}