Skip to content
Advertisement

How to Python gnupg (GPG) encrypt with recipient’s email address rather than their fingerprint?

How to Python-gnupg (GnuPG / GPG / OpenPGP) encrypt with recipient’s email address rather than their fingerprint?

This example shows (which failes on my Ubuntu 20.04 / such a thing, but it’s an old example; excerpt:

encrypted_data = gpg.encrypt(unencrypted_string, 'testgpguser@mydomain.com')

More-current (maybe?) references (like this and this) do not mention recipient email addresses, seemingly requiring numeric-only fingerprints for (presumably) public-key identication. Is it possible in today’s environment (to identify a key solely by it’s associated email_address/identity)? Possibly requiring a keyserver?

My tested python-gnupg system versions.

Advertisement

Answer

Looking at the version number in your question, you appear to be using the pretty-bad-protocol rewrite, which hasn’t been updated since 2018.

If you simply install python-gnupg:

$ pip install python-gnupg

You get version 0.4.9, which was released just a few days ago:

Collecting python-gnupg
  Downloading http://.../python_gnupg-0.4.9-py2.py3-none-any.whl (18 kB)
Installing collected packages: python-gnupg
Successfully installed python-gnupg-0.4.9

Using this version of the gnupg module, your code works without a problem:

>>> import gnupg
>>> gpg = gnupg.G
gnupg.GPG(     gnupg.GenKey(
>>> gpg = gnupg.GPG()
>>> res = gpg.encrypt("this is a test", "bob@example.com")
>>> res.data
b'-----BEGIN PGP MESSAGE-----n...n-----END PGP MESSAGE-----n'
>>>

It is of course better to use a fingerprint, because you may have multiple keys in your keychain with the same email address, and you can’t be certain which one you’ll get. Using a fingerprint ensures that you get that specific key.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement