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