fix: verify blob hash after download and decryption (closes #5) #39
@@ -5,30 +5,25 @@ import (
|
|||||||
"crypto/sha256"
|
"crypto/sha256"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"fmt"
|
"fmt"
|
||||||
"hash"
|
|
||||||
"io"
|
"io"
|
||||||
|
|
||||||
"filippo.io/age"
|
"filippo.io/age"
|
||||||
"git.eeqj.de/sneak/vaultik/internal/blobgen"
|
"git.eeqj.de/sneak/vaultik/internal/blobgen"
|
||||||
)
|
)
|
||||||
|
|
||||||
// hashVerifyReader wraps a reader and computes a double-SHA-256 hash of all
|
// hashVerifyReader wraps a blobgen.Reader and verifies the double-SHA-256 hash
|
||||||
// data read through it. The hash is verified against the expected blob hash
|
// of decrypted plaintext when Close is called. It reuses the hash that
|
||||||
// when Close is called. This allows streaming blob verification without
|
// blobgen.Reader already computes internally via its TeeReader, avoiding
|
||||||
// buffering the entire blob in memory.
|
// redundant SHA-256 computation.
|
||||||
type hashVerifyReader struct {
|
type hashVerifyReader struct {
|
||||||
reader io.ReadCloser // underlying decrypted blob reader
|
reader *blobgen.Reader // underlying decrypted blob reader (has internal hasher)
|
||||||
fetcher io.ReadCloser // raw fetched stream (closed on Close)
|
fetcher io.ReadCloser // raw fetched stream (closed on Close)
|
||||||
hasher hash.Hash // running SHA-256 of plaintext
|
blobHash string // expected double-SHA-256 hex
|
||||||
blobHash string // expected double-SHA-256 hex
|
done bool // EOF reached
|
||||||
done bool // EOF reached
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *hashVerifyReader) Read(p []byte) (int, error) {
|
func (h *hashVerifyReader) Read(p []byte) (int, error) {
|
||||||
n, err := h.reader.Read(p)
|
n, err := h.reader.Read(p)
|
||||||
if n > 0 {
|
|
||||||
h.hasher.Write(p[:n])
|
|
||||||
}
|
|
||||||
if err == io.EOF {
|
if err == io.EOF {
|
||||||
h.done = true
|
h.done = true
|
||||||
}
|
}
|
||||||
@@ -41,7 +36,7 @@ func (h *hashVerifyReader) Close() error {
|
|||||||
fetcherErr := h.fetcher.Close()
|
fetcherErr := h.fetcher.Close()
|
||||||
|
|
||||||
if h.done {
|
if h.done {
|
||||||
firstHash := h.hasher.Sum(nil)
|
firstHash := h.reader.Sum256()
|
||||||
secondHasher := sha256.New()
|
secondHasher := sha256.New()
|
||||||
secondHasher.Write(firstHash)
|
secondHasher.Write(firstHash)
|
||||||
actualHashHex := hex.EncodeToString(secondHasher.Sum(nil))
|
actualHashHex := hex.EncodeToString(secondHasher.Sum(nil))
|
||||||
@@ -75,7 +70,6 @@ func (v *Vaultik) FetchAndDecryptBlob(ctx context.Context, blobHash string, expe
|
|||||||
return &hashVerifyReader{
|
return &hashVerifyReader{
|
||||||
reader: reader,
|
reader: reader,
|
||||||
fetcher: rc,
|
fetcher: rc,
|
||||||
hasher: sha256.New(),
|
|
||||||
blobHash: blobHash,
|
blobHash: blobHash,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user