Skip to content

Commit

Permalink
Merge pull request #119 from multiformats/fix/large
Browse files Browse the repository at this point in the history
Ensure that length of multihash is properly handled
  • Loading branch information
Stebalien authored Dec 3, 2019
2 parents 4b0a826 + 44456e9 commit 572861f
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
6 changes: 6 additions & 0 deletions sum.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ import (
// ErrSumNotSupported is returned when the Sum function code is not implemented
var ErrSumNotSupported = errors.New("Function not implemented. Complain to lib maintainer.")

var ErrLenTooLarge = errors.New("requested length was too large for digest")

// HashFunc is a hash function that hashes data into digest.
//
// The length is the size the digest will be truncated to. While the hash
Expand Down Expand Up @@ -53,6 +55,10 @@ func Sum(data []byte, code uint64, length int) (Multihash, error) {
if err != nil {
return nil, err
}
if len(d) < length {
return nil, ErrLenTooLarge
}

if length >= 0 {
d = d[:length]
}
Expand Down
9 changes: 9 additions & 0 deletions sum_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ var sumTestCases = []SumTestCase{
{SHA1, -1, "foo", "11140beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33"},
{SHA1, 10, "foo", "110a0beec7b5ea3f0fdbc95d"},
{SHA2_256, -1, "foo", "12202c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"},
{SHA2_256, 31, "foo", "121f2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7"},
{SHA2_256, 32, "foo", "12202c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"},
{SHA2_256, 16, "foo", "12102c26b46b68ffc68ff99b453c1d304134"},
{SHA2_512, -1, "foo", "1340f7fbba6e0636f890e56fbbf3283e524c6fa3204ae298382d624741d0dc6638326e282c41be5e4254d8820772c5518a2c5a8c0c7f7eda19594a7eb539453e1ed7"},
{SHA2_512, 32, "foo", "1320f7fbba6e0636f890e56fbbf3283e524c6fa3204ae298382d624741d0dc663832"},
Expand Down Expand Up @@ -172,3 +174,10 @@ func TestRegisterHashFunc(t *testing.T) {
}
}
}

func TestTooLargeLength(t *testing.T) {
_, err := Sum([]byte("test"), SHA2_256, 33)
if err != ErrLenTooLarge {
t.Fatal("bad error", err)
}
}

0 comments on commit 572861f

Please sign in to comment.