Registry / auth-security / python-gnupg

python-gnupg

JSON →
library0.5.6pypypi✓ verified 27d ago

Python-GnuPG is a Python wrapper for the GNU Privacy Guard (GnuPG) command-line tool, enabling Python programs to perform cryptographic operations like encryption, decryption, digital signing, and key management. It provides a high-level, Pythonic interface to GnuPG's functionality. The library is actively maintained, with version 2.3.1 being the latest as of April 2026, and typically follows GnuPG's release cycle for compatibility updates.

pip install python-gnupg
INSTALL
IMPORT
SIG · PYTHON-GNUPG
P
python-gnupg
auth-securitypythonv0.5.6
Install
1.5s avg
Import
60ms
Disk
16MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.5.6 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.062s · 17.9MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 1.5s · import 0.058s · 18MB
16MB installed
● package 16MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

GPG
import gnupg gpg = gnupg.GPG()
from gnupg import GPG
The primary class 'GPG' is typically accessed as 'gnupg.GPG' after importing the top-level 'gnupg' module.

This quickstart demonstrates how to initialize the GPG object, generate a new key pair, encrypt a string using the generated public key, and then decrypt it using the corresponding private key and passphrase. It emphasizes the importance of setting a `gnupghome` directory for GnuPG operations.

import gnupg import os # Ensure the GnuPG home directory exists and has correct permissions gnupghome = os.path.expanduser('~/.gnupg_test') if not os.path.exists(gnupghome): os.makedirs(gnupghome, mode=0o700) gpg = gnupg.GPG(gnupghome=gnupghome) # Ensure the GnuPG binary path is correct if not in system PATH # gpg = gnupg.GPG(gnupghome=gnupghome, gpgbinary='/usr/local/bin/gpg') # Generate a key pair (example, use stronger keys and secure passphrases in production) passphrase = os.environ.get('GPG_PASSPHRASE', 'mysecurepassphrase') input_data = gpg.gen_key_input( key_type="RSA", key_length=2048, name_real="Test User", name_email="test@example.com", passphrase=passphrase ) key = gpg.gen_key(input_data) if key: print(f"Generated Key ID: {key.fingerprint}") # Encrypt a message message = "Hello, GnuPG! This is a secret message." encrypted_data = gpg.encrypt(message, recipients=[key.fingerprint], passphrase=passphrase) if encrypted_data.ok: print("\nEncrypted Message:") print(str(encrypted_data)) # Decrypt the message decrypted_data = gpg.decrypt(str(encrypted_data), passphrase=passphrase) if decrypted_data.ok: print("\nDecrypted Message:") print(str(decrypted_data)) assert str(decrypted_data) == message else: print(f"\nDecryption Failed: {decrypted_data.status}") print(f"Stderr: {decrypted_data.stderr}") else: print(f"\nEncryption Failed: {encrypted_data.status}") print(f"Stderr: {encrypted_data.stderr}") else: print(f"Key generation failed: {gpg.gen_key(input_data).stderr}")
Debug
Known issues
breakingGnuPG versions 2.1 and later changed passphrase handling. Programmatic passphrase input (e.g., for `gen_key`, `decrypt`) often requires `allow-loopback-pinentry` to be present in `gpg-agent.conf` within your GnuPG home directory. Without this, GnuPG might prompt interactively or fail, even if a passphrase is provided in the Python code.
fix
Add `allow-loopback-pinentry` as a single line to the `gpg-agent.conf` file in the GnuPG home directory being used by your application. Some specific 2.1.x versions may still exhibit unhelpful behavior. Ensure you have a recent, stable GnuPG executable.
affects: GnuPG >= 2.1 (not python-gnupg versions)
gotchaFile permissions for the GnuPG home directory (`gnupghome`) are critical. GnuPG is very particular about permissions (typically `0o700` or `rwx------` for the owner). Incorrect permissions can lead to 'secret key not available' or other unexpected failures, even if the key exists.
fix
Always ensure the directory specified for `gnupghome` (and its contents, especially keyrings) has strict permissions, ideally `chmod 0o700 /path/to/gnupghome`. When running in environments like web servers or Docker, verify the user executing the Python script has appropriate ownership and permissions.
affects: All
gotchaThe `gpgbinary` parameter to `gnupg.GPG()` is crucial if the `gpg` executable is not in the system's PATH. If `python-gnupg` cannot find the `gpg` binary, it will fail to initialize or execute GnuPG commands.
fix
Explicitly pass the full path to the GnuPG executable, e.g., `gpg = gnupg.GPG(gpgbinary='/usr/local/bin/gpg', gnupghome='...')`, or ensure `gpg` is discoverable via the system's PATH environment variable for the user running the Python script.
affects: All
deprecatedThe `secret_keyring` argument for `gnupg.GPG` is no longer used when working with GnuPG versions 2.1 and later, as GnuPG 2.1+ merges public and secret keyrings.
fix
Omit the `secret_keyring` argument when initializing `gnupg.GPG` if you are using GnuPG 2.1 or newer. The primary `keyring` argument should still be used if you need to specify a non-default keyring file name.
affects: python-gnupg versions used with GnuPG >= 2.1
gotchaDefault encoding for I/O with GnuPG commands changed from locale-based/UTF-8 to `latin-1` in `python-gnupg` version 0.3.7. Using the wrong encoding can lead to exceptions or data corruption, especially with non-ASCII characters.
fix
Set the `gpg.encoding` attribute explicitly to `utf-8` or another appropriate encoding if your data contains non-`latin-1` characters, especially when dealing with text. E.g., `gpg = gnupg.GPG(encoding='utf-8', ...)`.
affects: python-gnupg < 0.3.7 might have different defaults; all versions require careful encoding handling.
Errors
Common errors & fixes
FileNotFoundError: [Errno 2] No such file or directory: 'gpg'
The `gpg` executable, which `python-gnupg` wraps, is not installed on the system or is not discoverable in the system's PATH.
fix
Install GnuPG on your system and ensure its executable is in your system's PATH. Alternatively, specify the exact path to the `gpg` binary when initializing `gnupg.GPG`: `gpg = gnupg.GPG(gpgbinary='/usr/local/bin/gpg')`.
TypeError: a bytes-like object is required, not 'str'
`python-gnupg` functions like `encrypt`, `decrypt`, `sign`, or `verify` expect binary data (bytes) as input, but a Python string was provided.
fix
Encode the string to bytes (e.g., using `str.encode()`) before passing it to the GnuPG function: `encrypted_data = gpg.encrypt(plaintext_data.encode('utf-8'), recipients)`.
"decryption failed"
Decryption or signature verification failed because the necessary private key was not found in the keyring, the passphrase was incorrect, or the encrypted data was corrupted. The `gpg.decrypt()` or `gpg.verify()` method returns a result object with `ok=False` and this status.
fix
Ensure the correct private key is available in the `gnupghome` keyring, provide the correct passphrase using the `passphrase` argument, or verify the integrity and correct encryption of the input data. Check `result.stderr` for more detailed GnuPG error messages.
ValueError: GnuPG home directory does not exist: /path/to/gnupghome
The directory specified for `gnupghome`, which GnuPG uses for keyrings and configuration, does not exist on the filesystem or is inaccessible.
fix
Create the `gnupghome` directory manually or programmatically with appropriate permissions before initializing `gnupg.GPG`: `import os; os.makedirs('/path/to/gnupghome', exist_ok=True); gpg = gnupg.GPG(gnupghome='/path/to/gnupghome')`.
Upgrade
Version history
0.5.6latest on PyPI · released Dec 31, 2025
Audit
Dependencies
GnuPGrequiredThis library is a wrapper around the GnuPG command-line tool; the 'gpg' executable must be installed and accessible on the system.
Agent activity
24 hits · last 30 days
node
20
OpenAI (training)
1
Resources
python-gnupg — pip install python-gnupg · libregistry