passforios-gopenpgp/crypto/attachment.go

186 lines
5 KiB
Go
Raw Normal View History

package crypto
2018-06-04 16:05:14 -07:00
import (
"bytes"
"io"
"io/ioutil"
2018-11-22 10:53:14 +01:00
"runtime"
"sync"
"time"
2018-06-04 16:05:14 -07:00
"github.com/ProtonMail/go-crypto/openpgp"
"github.com/ProtonMail/go-crypto/openpgp/packet"
"github.com/pkg/errors"
2018-06-04 16:05:14 -07:00
)
// AttachmentProcessor keeps track of the progress of encrypting an attachment
// (optimized for encrypting large files).
2018-11-22 10:53:14 +01:00
type AttachmentProcessor struct {
w *io.WriteCloser
pipe *io.PipeWriter
done sync.WaitGroup
split *PGPSplitMessage
2018-11-22 10:53:14 +01:00
garbageCollector int
err error
}
// Process writes attachment data to be encrypted.
2018-11-22 10:53:14 +01:00
func (ap *AttachmentProcessor) Process(plainData []byte) {
if _, err := (*ap.w).Write(plainData); err != nil {
panic(err)
}
if ap.garbageCollector > 0 {
defer runtime.GC()
}
2018-11-22 10:53:14 +01:00
}
// Finish closes the attachment and returns the encrypted data.
func (ap *AttachmentProcessor) Finish() (*PGPSplitMessage, error) {
2018-11-22 10:53:14 +01:00
if ap.err != nil {
return nil, ap.err
}
if err := (*ap.w).Close(); err != nil {
return nil, errors.Wrap(err, "gopengpp: unable to close writer")
}
if ap.garbageCollector > 0 {
ap.w = nil
runtime.GC()
}
if err := (*ap.pipe).Close(); err != nil {
return nil, errors.Wrap(err, "gopengpp: unable to close pipe")
}
2018-11-22 10:53:14 +01:00
ap.done.Wait()
if ap.err != nil {
return nil, ap.err
}
splitMsg := ap.split
2018-11-22 10:53:14 +01:00
if ap.garbageCollector > 0 {
ap.pipe = nil
ap.split = nil
defer runtime.GC()
2018-06-04 16:05:14 -07:00
}
return splitMsg, nil
2018-11-22 10:53:14 +01:00
}
// newAttachmentProcessor creates an AttachmentProcessor which can be used to encrypt
// a file. It takes an estimatedSize and fileName as hints about the file.
func (keyRing *KeyRing) newAttachmentProcessor(
2022-02-15 11:57:30 +01:00
estimatedSize int, filename string, isBinary bool, modTime uint32, garbageCollector int, //nolint:unparam
) (*AttachmentProcessor, error) {
2018-11-22 10:53:14 +01:00
attachmentProc := &AttachmentProcessor{}
// You could also add these one at a time if needed.
2018-11-22 10:53:14 +01:00
attachmentProc.done.Add(1)
attachmentProc.garbageCollector = garbageCollector
2018-06-04 16:05:14 -07:00
hints := &openpgp.FileHints{
FileName: filename,
IsBinary: isBinary,
ModTime: time.Unix(int64(modTime), 0),
2018-06-04 16:05:14 -07:00
}
config := &packet.Config{
DefaultCipher: packet.CipherAES256,
Time: getTimeGenerator(),
}
2018-06-04 16:05:14 -07:00
2018-11-22 10:53:14 +01:00
reader, writer := io.Pipe()
go func() {
defer attachmentProc.done.Done()
ciphertext, _ := ioutil.ReadAll(reader)
message := &PGPMessage{
Data: ciphertext,
}
split, splitError := message.SplitMessage()
if attachmentProc.err == nil {
2018-11-22 10:53:14 +01:00
attachmentProc.err = splitError
}
attachmentProc.split = split
}()
var ew io.WriteCloser
var encryptErr error
ew, encryptErr = openpgp.Encrypt(writer, keyRing.entities, nil, hints, config)
if encryptErr != nil {
return nil, errors.Wrap(encryptErr, "gopengpp: unable to encrypt attachment")
}
2018-11-22 10:53:14 +01:00
attachmentProc.w = &ew
attachmentProc.pipe = writer
return attachmentProc, nil
}
2018-06-04 16:05:14 -07:00
// EncryptAttachment encrypts a file given a PlainMessage and a filename.
// If given a filename it will override the information in the PlainMessage object.
// Returns a PGPSplitMessage containing a session key packet and symmetrically encrypted data.
// Specifically designed for attachments rather than text messages.
func (keyRing *KeyRing) EncryptAttachment(message *PlainMessage, filename string) (*PGPSplitMessage, error) {
if filename == "" {
2020-10-13 13:14:09 +02:00
filename = message.Filename
}
ap, err := keyRing.newAttachmentProcessor(
len(message.GetBinary()),
filename,
message.IsBinary(),
message.Time,
-1,
)
2018-11-22 10:53:14 +01:00
if err != nil {
return nil, err
}
ap.Process(message.GetBinary())
2018-11-22 10:53:14 +01:00
split, err := ap.Finish()
2018-06-04 16:05:14 -07:00
if err != nil {
return nil, err
}
2018-06-04 17:50:26 -07:00
return split, nil
2018-11-22 10:53:14 +01:00
}
// NewLowMemoryAttachmentProcessor creates an AttachmentProcessor which can be used
2020-10-13 13:14:09 +02:00
// to encrypt a file. It takes an estimatedSize and filename as hints about the
// file. It is optimized for low-memory environments and collects garbage every
// megabyte.
func (keyRing *KeyRing) NewLowMemoryAttachmentProcessor(
estimatedSize int, filename string,
) (*AttachmentProcessor, error) {
return keyRing.newAttachmentProcessor(estimatedSize, filename, true, uint32(GetUnixTime()), 1<<20)
2018-06-04 16:05:14 -07:00
}
// DecryptAttachment takes a PGPSplitMessage, containing a session key packet and symmetrically encrypted data
// and returns a decrypted PlainMessage
// Specifically designed for attachments rather than text messages.
func (keyRing *KeyRing) DecryptAttachment(message *PGPSplitMessage) (*PlainMessage, error) {
privKeyEntries := keyRing.entities
2019-08-19 12:06:30 +02:00
keyReader := bytes.NewReader(message.GetBinaryKeyPacket())
dataReader := bytes.NewReader(message.GetBinaryDataPacket())
2018-06-04 16:05:14 -07:00
encryptedReader := io.MultiReader(keyReader, dataReader)
config := &packet.Config{Time: getTimeGenerator()}
md, err := openpgp.ReadMessage(encryptedReader, privKeyEntries, nil, config)
2018-06-04 16:05:14 -07:00
if err != nil {
return nil, errors.Wrap(err, "gopengpp: unable to read attachment")
2018-06-04 16:05:14 -07:00
}
decrypted := md.UnverifiedBody
b, err := ioutil.ReadAll(decrypted)
if err != nil {
return nil, errors.Wrap(err, "gopengpp: unable to read attachment body")
2018-06-04 16:05:14 -07:00
}
return &PlainMessage{
Data: b,
TextType: !md.LiteralData.IsBinary,
2020-10-13 13:14:09 +02:00
Filename: md.LiteralData.FileName,
Time: md.LiteralData.Time,
}, nil
2018-06-04 16:05:14 -07:00
}