Scott
Scott

Reputation: 1296

Python gnupg encrypt_file(StringIO()) creates encrypted PGP message with empty content?

I don't understand what I'm doing wrong here. As far as I can tell from the python gnupg documentation this encrypt_file call should have content like the encrypt call, but everything I'm trying is resulting in a GPG blob that decrypts to a blank file. No error, no indication that there was any problem with the operation, just... emptyness, like it was compiled with sartre=1...

Am I missing some key to the incantation?

Python 3.6.5, python-gnupg==0.4.7

from gnupg import GPG
from io import StringIO

gpg = GPG(gpgbinary='/usr/local/bin/gpg', gnupghome='/tmp/gpg/')
keyserver = <insert keyserver URI>
fp = <insert GPG key fingerprint>
gpg.recv_keys(keyserver, fp)

sio = StringIO('\n'.join([f"Hello world {n}" for n in range(120)]))

c0 = gpg.encrypt(sio.getvalue(), recipients=fp)
len(str(c0))
1252

c1 = gpg.encrypt_file(sio, recipients=fp)
len(str(c1))
858

sio = StringIO('\n'.join([f"Hello world {n}" for n in range(1200)]))

c0 = gpg.encrypt(sio.getvalue(), recipients=fp)
len(str(c0))
4559

c1 = gpg.encrypt_file(sio, recipients=fp)
len(str(c1))
858

Upvotes: 0

Views: 743

Answers (1)

Scott
Scott

Reputation: 1296

Seems the following were the operative issues:

  • The file-like object, it seems, has to be binary; e.g. a BytesIO or a file pointer opened in binary mode.
  • You have to seek(0) to write the full content of the file-like object. (Kind of obvious but I overlooked it; I probably kept checking encrypt() first then encrypt_file() without seeking back to the start. It probably didn't help that this doesn't make it work on a StringIO, so I may have mentally ruled it out as the issue early on.)

Upvotes: 2

Related Questions