-
-
Notifications
You must be signed in to change notification settings - Fork 114
/
data_with_hash.go
55 lines (50 loc) · 1.26 KB
/
data_with_hash.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package crypto
import (
"bytes"
"crypto/sha1" // #nosec
"io"
)
// GuessDataWithHash guesses data from data_with_hash.
func GuessDataWithHash(dataWithHash []byte) []byte {
// data_with_hash := SHA1(data) + data + (0-15 random bytes);
// such that length be divisible by 16;
if len(dataWithHash) <= sha1.Size {
// Data length too small.
return nil
}
v := dataWithHash[:sha1.Size]
for i := 0; i < 16; i++ {
if len(dataWithHash)-i < sha1.Size {
// End of slice reached.
return nil
}
data := dataWithHash[sha1.Size : len(dataWithHash)-i]
h := sha1.Sum(data) // #nosec
if bytes.Equal(h[:], v) {
// Found.
return data
}
}
return nil
}
func paddedLen16(l int) int {
n := 16 * (l / 16)
if n < l {
n += 16
}
return n
}
// DataWithHash prepends data with SHA1(data) and 0..15 random bytes so result
// length is divisible by 16.
//
// Use GuessDataWithHash(result) to obtain data.
func DataWithHash(data []byte, randomSource io.Reader) ([]byte, error) {
dataWithHash := make([]byte, paddedLen16(len(data)+sha1.Size))
h := sha1.Sum(data) // #nosec
copy(dataWithHash, h[:])
copy(dataWithHash[sha1.Size:], data)
if _, err := io.ReadFull(randomSource, dataWithHash[sha1.Size+len(data):]); err != nil {
return nil, err
}
return dataWithHash, nil
}