Skip to content

Commit a0545ef

Browse files
authored
Merge pull request #77 from schomatis/fix/sum/id-hash-len
sum: check length of identity hash
2 parents c5fd85e + dd7e632 commit a0545ef

File tree

2 files changed

+38
-3
lines changed

2 files changed

+38
-3
lines changed

sum.go

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ func Sum(data []byte, code uint64, length int) (Multihash, error) {
5252
default:
5353
switch code {
5454
case ID:
55-
d = sumID(data)
55+
d, err = sumID(data, length)
5656
case SHA1:
5757
d = sumSHA1(data)
5858
case SHA2_256:
@@ -116,8 +116,13 @@ func sumBlake2b(size uint8, data []byte) []byte {
116116
return hasher.Sum(nil)[:]
117117
}
118118

119-
func sumID(data []byte) []byte {
120-
return data
119+
func sumID(data []byte, length int) ([]byte, error) {
120+
if length >= 0 && length != len(data) {
121+
return nil, fmt.Errorf("the length of the identity hash (%d) must be equal to the length of the data (%d)",
122+
length, len(data))
123+
124+
}
125+
return data, nil
121126
}
122127

123128
func sumSHA1(data []byte) []byte {

sum_test.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,3 +120,33 @@ func BenchmarkBlake2B(b *testing.B) {
120120
}(s)
121121
}
122122
}
123+
124+
// Test that the identity hash function checks
125+
// its `length` arguemnt for values that are
126+
// different to its `data` length.
127+
func TestSmallerLengthHashID(t *testing.T) {
128+
129+
data := []byte("Identity hash input data.")
130+
dataLength := len(data)
131+
132+
// Normal case: `length == len(data)`.
133+
_, err := sumID(data, dataLength)
134+
if err != nil {
135+
t.Fatal(err)
136+
}
137+
138+
// Unconstrained length (-1): also allowed.
139+
_, err = sumID(data, -1)
140+
if err != nil {
141+
t.Fatal(err)
142+
}
143+
144+
// Any other variation of those two scenarios should fail.
145+
for l := (dataLength - 1); l >= 0; l-- {
146+
_, err = sumID(data, l)
147+
if err == nil {
148+
t.Fatal(fmt.Sprintf("identity hash of length %d smaller than data length %d didn't fail",
149+
l, dataLength))
150+
}
151+
}
152+
}

0 commit comments

Comments
 (0)