or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

encryption-decryption.mdgpg-instance.mdindex.mdkey-discovery.mdkey-management.mdkeyserver-operations.mdsigning-verification.md
tile.json

tessl/pypi-python-gnupg

A wrapper for the Gnu Privacy Guard (GPG or GnuPG)

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/python-gnupg@0.5.x

To install, run

npx @tessl/cli install tessl/pypi-python-gnupg@0.5.0

index.mddocs/

Python GnuPG

A 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.

Package Information

  • Package Name: python-gnupg
  • Language: Python
  • Installation: pip install python-gnupg

Core Imports

import gnupg

Basic Usage

import 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 valid

Architecture

The 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:

  • GPG Class: Main interface providing all cryptographic operations
  • Result Objects: Operation-specific classes (Verify, ImportResult, Crypt, etc.) that contain status information and results
  • Status Handling: Internal status message processing from the GPG subprocess
  • Platform Support: Cross-platform compatibility with Windows and Unix/Linux systems

Capabilities

GPG Instance Management

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): ...

GPG Instance Management

Key Management Operations

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): ...

Key Management

Encryption and Decryption

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): ...

Encryption and Decryption

Digital Signing and Verification

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 Operations

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): ...

Keyserver Operations

Key Discovery and Analysis

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): ...

Key Discovery and Analysis

Module Information

# 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
    """

Common Types

# 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