Skip to content

Commit e299562

Browse files
committed
Reuse same hash; Check if preimage matches
1 parent 6df39e0 commit e299562

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

pkg/decrypt.go

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,16 @@ import (
1313
//
1414
// If chunk index is not -1, then error occurred while decrypting the chunk
1515
// hence proof for given chunk should be generated.
16-
func Decrypt(preimage []byte, file io.ReadSeeker, chunkSize int64) (io.Reader, int, error) {
16+
func Decrypt(paymentHash []byte, preimage []byte, file io.ReadSeeker, chunkSize int64) (io.Reader, int, error) {
1717
var out bytes.Buffer
18+
h := sha256.New()
19+
h.Write(preimage)
20+
preimageHash := h.Sum(nil)
21+
22+
// check if preimage hash matches payment hash
23+
if !bytes.Equal(preimageHash, paymentHash) {
24+
return nil, -1, fmt.Errorf("preimage hash does not match payment hash. expected %x got %x", paymentHash, preimageHash)
25+
}
1826

1927
expectedHash := make([]byte, HashSize)
2028
encryptedChunk := make([]byte, chunkSize)
@@ -62,7 +70,7 @@ func Decrypt(preimage []byte, file io.ReadSeeker, chunkSize int64) (io.Reader, i
6270

6371
// decrypt chunk, compute hash and if hashes match
6472
decryptedChunk := ChunkCipher(i, preimage, encryptedChunk)
65-
h := sha256.New()
73+
h.Reset()
6674
h.Write(decryptedChunk)
6775
hash := h.Sum(nil)
6876
if !bytes.Equal(expectedHash, hash) {

pkg/encrypt.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ func EncryptFile(preimage []byte, file io.ReadSeeker, chunkSize int64) (Encrypte
6060
nodes []*Node
6161
)
6262

63+
h := sha256.New()
6364
for {
6465
chunk := make([]byte, chunkSize)
6566
n, err := chunks.Read(chunk)
@@ -71,7 +72,7 @@ func EncryptFile(preimage []byte, file io.ReadSeeker, chunkSize int64) (Encrypte
7172
return nil, nil, err
7273
}
7374

74-
h := sha256.New()
75+
h.Reset()
7576
h.Write(chunk)
7677
hash := h.Sum(nil)
7778

0 commit comments

Comments
 (0)