Python-gnupg cant find secret key

703 Views Asked by At

I have an Ubuntu 20.04 server. On the server I am running a python script to decrypt some PGP encrypted files. I have added the PGP keys to a keyring and can decrypt a file using the command line:

gpg --output test.zip --decrypt myfile.pgp

The Python script is using python-gnupg. Please see below my extract.

import gnupg
gpg = gnupg.GPG(gpgbinary='/usr/bin/gpg')       
stream = open('myfile.pgp', "rb")
data = gpg.decrypt_file(stream, output=f'output.zip') 
print(data.status)

The issue is that when I run this Python code the private key cannot be found. The data.status returns 'no secret key'. However if I run the code shortly after running the command line decrypt - the decryption works - data.status returns 'decryption ok'

This must be because following the command line statement the key is briefly available to the script.

I have tried specifying the directory for the key in the Python script - but this didn't make a difference.

When I run with verbose=True the error seems to be related to the following:

gpg: public key decryption failed: Inappropriate ioctl for device 

Any help would be much appreciated

1

There are 1 best solutions below

1
On BEST ANSWER

When you attempt to decrypt the data, GPG needs to prompt for the passphrase to your private key. It looks like it is failing to do so. It probably works after running the command line because there is a gpg-agent or other keyring process running that caches the decrypted key for some period of time.

How does gpg usually prompt you for a passphrase? If it's configured to use the terminal by default, you may want to configure it to use a GUI prompt instead (e.g., pinentry-gnome3). You can read about configuring the pinentry mechanism here.