Skip to content

feature: Make age.Encrypt not write already to the writer. #654

@gabyx

Description

@gabyx

I think awesome library would benefit from having age.Encrypt

  • not yet write anything to the returned writer (but do that on the first write).
  • making the writer creation non-blocking is nice (see below).

The conclusion for that come from trying to wrap an src io.Reader to an encrypted reader (ot be used in other applications, e.g. pushing to an S3 etc).

The following doEncrypt will block cause pr is not yet read when age.Encrypt is called -> block.

package main

import (
	"bytes"
	"fmt"
	"io"

	"filippo.io/age"
)

func wrapEncrypt(src io.Reader) (io.Reader, error) {
	publicKey := "age1cy0su9fwf3gf9mw868g5yut09p6nytfmmnktexz2ya5uqg9vl9sss4euqm"
	recipient, err := age.ParseX25519Recipient(publicKey)
	if err != nil {
		return nil, err
	}

	rp, wp := io.Pipe()
	encryptedWrite, err := age.Encrypt(wp, recipient)
	if err != nil {
		return nil, err
	}

	_, err = io.Copy(encryptedWrite, src)
	if err != nil {
		return nil, err
	}
	defer encryptedWrite.Close()

	return rp, nil
}

func main() {
	inputStr := "this is some secret thing"
	input := bytes.NewBufferString(inputStr)
	output, err := wrapEncrypt(input)
	if err != nil {
		panic(err)
	}
	encryptedContents, err := io.ReadAll(output)
	if err != nil {
		panic(err)
	}
	fmt.Println(inputStr)
	fmt.Println()
	fmt.Println(string(encryptedContents))
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions