A wrapper for the Gnu Privacy Guard (GPG or GnuPG)
npx @tessl/cli install tessl/pypi-python-gnupg@0.5.0A comprehensive Python wrapper for the GNU Privacy Guard (GPG/GnuPG) command-line tool. This library enables developers to integrate cryptographic operations into Python applications through a high-level interface for key management, encryption/decryption, digital signing, signature verification, and keyring operations.
pip install python-gnupgimport gnupgimport gnupg
# Create GPG instance with default settings
gpg = gnupg.GPG()
# Or with custom GPG home directory
gpg = gnupg.GPG(gnupghome='/path/to/gnupg/home')
# Generate a key pair
input_data = gpg.gen_key_input(
name_real='John Doe',
name_email='john@example.com',
passphrase='my_passphrase'
)
key = gpg.gen_key(input_data)
# Encrypt data
encrypted_data = gpg.encrypt('Hello, World!', recipients=['john@example.com'])
print(encrypted_data.ok) # True if successful
print(str(encrypted_data)) # Encrypted ASCII-armored data
# Decrypt data
decrypted_data = gpg.decrypt(str(encrypted_data), passphrase='my_passphrase')
print(decrypted_data.ok) # True if successful
print(str(decrypted_data)) # 'Hello, World!'
# Sign data
signed_data = gpg.sign('Hello, World!', passphrase='my_passphrase')
print(signed_data.status) # Status of signing operation
# Verify signature
verified = gpg.verify(str(signed_data))
print(verified.valid) # True if signature is validThe library follows a consistent pattern where operations are performed via the main GPG class methods, which return specialized result objects containing operation outcomes and any retrieved data:
Core GPG instance creation and configuration, supporting custom binary paths, keyring locations, and environment settings.
class GPG:
def __init__(self, gpgbinary='gpg', gnupghome=None, verbose=False,
use_agent=False, keyring=None, options=None,
secret_keyring=None, env=None): ...Comprehensive key management including generation, import, export, deletion, and keyring operations. Supports both local keyring operations and keyserver interactions.
def gen_key(self, input): ...
def gen_key_input(self, **kwargs): ...
def import_keys(self, key_data, extra_args=None, passphrase=None): ...
def export_keys(self, keyids, secret=False, armor=True, minimal=False,
passphrase=None, expect_passphrase=True, output=None): ...
def delete_keys(self, fingerprints, secret=False, **kwargs): ...
def list_keys(self, secret=False, keys=None, sigs=False): ...Symmetric and asymmetric encryption/decryption operations supporting files, strings, and streams with comprehensive configuration options.
def encrypt(self, data, recipients, **kwargs): ...
def encrypt_file(self, fileobj_or_path, recipients, **kwargs): ...
def decrypt(self, message, **kwargs): ...
def decrypt_file(self, fileobj_or_path, **kwargs): ...
def get_recipients(self, message, **kwargs): ...Digital signature creation and verification for data integrity and authenticity, supporting detached signatures, clear-text signing, and comprehensive verification.
def sign(self, message, **kwargs): ...
def sign_file(self, fileobj_or_path, **kwargs): ...
def verify(self, data, **kwargs): ...
def verify_file(self, fileobj_or_path, **kwargs): ...
def verify_data(self, sig_filename, data, **kwargs): ...Digital Signing and Verification
Keyserver interactions for publishing, retrieving, and searching public keys across distributed keyserver networks.
def recv_keys(self, keyserver, *keyids, **kwargs): ...
def send_keys(self, keyserver, *keyids, **kwargs): ...
def search_keys(self, query, keyserver='pgp.mit.edu', **kwargs): ...
def auto_locate_key(self, email, mechanisms=None, **kwargs): ...Advanced key discovery, scanning, and analysis operations for examining keys without importing them and understanding key structures.
def scan_keys(self, filename): ...
def scan_keys_mem(self, key_data): ...
def trust_keys(self, fingerprints, trustlevel): ...
def add_subkey(self, master_key, **kwargs): ...# Module metadata
__version__: str = '0.5.5' # Library version
__author__: str = 'Vinay Sajip'
__date__: str = '$04-Aug-2025 19:49:23$'
# Utility functions
def shell_quote(s):
"""
Quote text for safe shell usage.
Parameters:
- s (str): String to quote
Returns:
str: Shell-safe quoted string
"""# Result object base properties (common to all result types)
class StatusHandler:
status: str # Operation status message
stderr: str # Error output from GPG
returncode: int # GPG process return code
# Main result types
class Verify(StatusHandler):
valid: bool # True if signature is valid
fingerprint: str # Signer's key fingerprint
username: str # Signer's username
trust_level: int # Trust level of the key (0-5)
trust_text: str # Human-readable trust level
creation_date: str # Signature creation date
signature_id: str # Signature identifier
# Trust level constants
TRUST_EXPIRED: int = 0
TRUST_UNDEFINED: int = 1
TRUST_NEVER: int = 2
TRUST_MARGINAL: int = 3
TRUST_FULLY: int = 4
TRUST_ULTIMATE: int = 5
TRUST_LEVELS: dict # Mapping of trust level names to values
class Crypt(StatusHandler):
ok: bool # True if operation succeeded
data: str # Encrypted/decrypted data
class ImportResult(StatusHandler):
count: int # Total keys processed
imported: int # Keys successfully imported
fingerprints: list # List of imported key fingerprints
class GenKey(StatusHandler):
fingerprint: str # Generated key fingerprint
class ListKeys(list):
# List of key dictionaries with fingerprint, uids, etc.
pass
class SendResult(StatusHandler):
# Result of keyserver send operations
pass
class Sign(StatusHandler):
data: str # Signed data
fingerprint: str # Signing key fingerprint