Skip to content

Commit

Permalink
Buffer decrypted bytes more efficiently
Browse files Browse the repository at this point in the history
  • Loading branch information
twiss committed Dec 16, 2024
1 parent 04cfaf2 commit df3ee02
Showing 1 changed file with 10 additions and 13 deletions.
23 changes: 10 additions & 13 deletions openpgp/packet/aead_crypter.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
package packet

import (
"bytes"
"crypto/cipher"
"encoding/binary"
"io"
Expand Down Expand Up @@ -59,20 +58,22 @@ func (wo *aeadCrypter) incrementIndex() error {
// aeadDecrypter reads and decrypts bytes. It buffers extra decrypted bytes when
// necessary, similar to aeadEncrypter.
type aeadDecrypter struct {
aeadCrypter // Embedded ciphertext opener
reader io.Reader // 'reader' is a partialLengthReader
aeadCrypter // Embedded ciphertext opener
reader io.Reader // 'reader' is a partialLengthReader
chunkBytes []byte
peekedBytes []byte // Used to detect last chunk
buffer bytes.Buffer // Buffered decrypted bytes
peekedBytes []byte // Used to detect last chunk
buffer []byte // Buffered decrypted bytes
}

// Read decrypts bytes and reads them into dst. It decrypts when necessary and
// buffers extra decrypted bytes. It returns the number of bytes copied into dst
// and an error.
func (ar *aeadDecrypter) Read(dst []byte) (n int, err error) {
// Return buffered plaintext bytes from previous calls
if ar.buffer.Len() > 0 {
return ar.buffer.Read(dst)
if len(ar.buffer) > 0 {
n = copy(dst, ar.buffer)
ar.buffer = ar.buffer[n:]
return
}

// Read a chunk
Expand All @@ -92,12 +93,8 @@ func (ar *aeadDecrypter) Read(dst []byte) (n int, err error) {
}

// Return decrypted bytes, buffering if necessary
if len(dst) < len(decrypted) {
n = copy(dst, decrypted[:len(dst)])
ar.buffer.Write(decrypted[len(dst):])
} else {
n = copy(dst, decrypted)
}
n = copy(dst, decrypted)
ar.buffer = decrypted[n:]
return
}

Expand Down

0 comments on commit df3ee02

Please sign in to comment.