age: add ExampleDecryptReaderAt with zip.NewReader

This commit is contained in:
Filippo Valsorda
2025-12-26 21:35:42 +01:00
parent 2ff5d341f6
commit da2191789a
3 changed files with 44 additions and 2 deletions

4
age.go
View File

@@ -284,8 +284,8 @@ func Decrypt(src io.Reader, identities ...Identity) (io.Reader, error) {
// DecryptReaderAt takes an underlying [io.ReaderAt] and its total encrypted
// size, and returns a ReaderAt of the decrypted plaintext and the plaintext
// size. These can be used for example to instantiate an [io.SectionReader],
// which implements [io.Reader] and [io.Seeker]. Note that ReaderAt by
// definition disregards the seek position of src.
// which implements [io.Reader] and [io.Seeker], or for [zip.NewReader].
// Note that ReaderAt by definition disregards the seek position of src.
//
// The ReadAt method of the returned ReaderAt can be called concurrently.
// The ReaderAt will internally cache the most recently decrypted chunk.

View File

@@ -5,10 +5,12 @@
package age_test
import (
"archive/zip"
"bytes"
"errors"
"fmt"
"io"
"io/fs"
"log"
"os"
"slices"
@@ -191,6 +193,40 @@ func TestEncryptDecryptScrypt(t *testing.T) {
}
}
func ExampleDecryptReaderAt() {
identity, err := age.ParseX25519Identity(privateKey)
if err != nil {
log.Fatalf("Failed to parse private key: %v", err)
}
f, err := os.Open("testdata/example.zip.age")
if err != nil {
log.Fatalf("Failed to open file: %v", err)
}
stat, err := f.Stat()
if err != nil {
log.Fatalf("Failed to stat file: %v", err)
}
r, size, err := age.DecryptReaderAt(f, stat.Size(), identity)
if err != nil {
log.Fatalf("Failed to open encrypted file: %v", err)
}
z, err := zip.NewReader(r, size)
if err != nil {
log.Fatalf("Failed to open zip: %v", err)
}
contents, err := fs.ReadFile(z, "example.txt")
if err != nil {
log.Fatalf("Failed to read file from zip: %v", err)
}
fmt.Printf("File contents: %q\n", contents)
// Output:
// File contents: "Black lives matter."
}
func TestParseIdentities(t *testing.T) {
tests := []struct {
name string

6
testdata/example.zip.age vendored Normal file
View File

@@ -0,0 +1,6 @@
age-encryption.org/v1
-> X25519 5CD81lZA72aQi0v6EnniOGkwaswpZ0AxCZNdiUVzP04
ol9DvdkiZWeRI4vMKRBVNxowDKwir4UPqYinSM5zqUI
--- 2tyNGCaPoT6UnuOy7sQJf1eXn4pb7z2ukSgTDIxrJxU
W
ï¡dtUb¸T ³¹0°ãÇ(àyKAPdr1‡M~ï ÄóÝkX>—ªËÌÑcÜ<63>[ƒ$à9», Gß{턚Fý‰ÂÁtkåÌ*}â9˜T®ÅÄÞ±®hLÐ<4C>çÙWƒ-Rdª˜üË£‡÷ÒH¿SdUà <E280B9>¬˜…ÄšFsÈìÀ2y+)æô]/ðÞ,k=Æ8(XŒ”íRÇAÖ×01RÃëY®Š»ƒ·ŽÌ •k4N§†6ÓÚt«v¬çÀb­<62>êc Þ_F0dêvÚxî ×ÛÏ$Xø~ /