A wrapper for the Gnu Privacy Guard (GPG or GnuPG)
—
Comprehensive key management operations including generation, import, export, deletion, and keyring manipulation for maintaining cryptographic keys.
Generate new GPG key pairs with configurable parameters for cryptographic strength, expiration, and identity information.
def gen_key(self, input):
"""
Generate a key pair using the provided input parameters.
Parameters:
- input (str): Key generation parameters (use gen_key_input() to create)
Returns:
GenKey: Result object with fingerprint and status information
"""
def gen_key_input(self, **kwargs):
"""
Generate input parameters for key generation.
Parameters:
- key_type (str): Key algorithm ('RSA', 'DSA', 'ECDSA', 'EDDSA')
- key_length (int): Key length in bits (1024, 2048, 4096)
- key_curve (str): Curve for ECC keys ('nistp256', 'nistp384', 'nistp521', 'brainpoolP256r1', etc.)
- subkey_type (str): Subkey algorithm
- subkey_length (int): Subkey length in bits
- subkey_curve (str): Subkey curve for ECC
- name_real (str): Real name for the key
- name_comment (str): Comment for the key
- name_email (str): Email address for the key
- expire_date (str): Expiration date ('0' for no expiration, 'YYYY-MM-DD', '2y', '6m', etc.)
- passphrase (str): Passphrase to protect the private key
- preferences (str): Algorithm preferences
- revoker (str): Designated revoker
- keyserver (str): Preferred keyserver
Returns:
str: Formatted input string for gen_key()
"""
def add_subkey(self, master_key, master_passphrase=None, algorithm='rsa',
usage='encrypt', expire='-'):
"""
Add a subkey to an existing master key.
Parameters:
- master_key (str): Master key fingerprint or ID
- master_passphrase (str): Passphrase for the master key
- algorithm (str): Subkey algorithm ('rsa', 'dsa', 'ecdsa', 'eddsa')
- usage (str): Key usage ('encrypt', 'sign', 'auth')
- expire (str): Expiration setting ('-' for same as master, '0' for no expiration)
Returns:
AddSubkey: Result object with subkey information
"""Import keys from various sources and export keys in different formats for sharing and backup purposes.
def import_keys(self, key_data, extra_args=None, passphrase=None):
"""
Import key data into the keyring.
Parameters:
- key_data (str): ASCII-armored or binary key data
- extra_args (list): Additional GPG arguments
- passphrase (str): Passphrase for encrypted key data
Returns:
ImportResult: Result with import statistics and fingerprints
"""
def import_keys_file(self, key_path, **kwargs):
"""
Import keys from a file.
Parameters:
- key_path (str): Path to key file
- **kwargs: Additional arguments passed to import_keys()
Returns:
ImportResult: Result with import statistics
"""
def export_keys(self, keyids, secret=False, armor=True, minimal=False,
passphrase=None, expect_passphrase=True, output=None,
extra_args=None):
"""
Export keys from the keyring.
Parameters:
- keyids (str|list): Key IDs, fingerprints, or email addresses to export
- secret (bool): Export secret keys if True
- armor (bool): ASCII-armor the output
- minimal (bool): Export minimal key information
- passphrase (str): Passphrase for secret key export
- expect_passphrase (bool): Whether to expect passphrase prompt
- output (str): Output file path
- extra_args (list): Additional GPG arguments
Returns:
ExportResult: Result with exported key data
"""Discover and list keys in keyrings with detailed information about key properties, signatures, and relationships.
def list_keys(self, secret=False, keys=None, sigs=False):
"""
List keys in the keyring.
Parameters:
- secret (bool): List secret keys if True, public keys if False
- keys (list): Specific keys to list (default: all keys)
- sigs (bool): Include signature information
Returns:
ListKeys: List of key dictionaries with detailed information
"""
def scan_keys(self, filename):
"""
Scan keys from a file without importing them.
Parameters:
- filename (str): Path to key file to scan
Returns:
ScanKeys: List of key information without importing
"""
def scan_keys_mem(self, key_data):
"""
Scan keys from memory without importing them.
Parameters:
- key_data (str): Key data to scan
Returns:
ScanKeys: List of key information without importing
"""Remove keys from keyrings and manage trust levels for web-of-trust operations.
def delete_keys(self, fingerprints, secret=False, passphrase=None,
expect_passphrase=True, exclamation_mode=False):
"""
Delete keys from the keyring.
Parameters:
- fingerprints (str|list): Key fingerprints to delete
- secret (bool): Delete secret keys if True
- passphrase (str): Passphrase for secret key deletion
- expect_passphrase (bool): Whether to expect passphrase prompt
- exclamation_mode (bool): Force deletion without confirmation
Returns:
DeleteResult: Result with deletion status
"""
def trust_keys(self, fingerprints, trustlevel):
"""
Set trust level for keys in the web of trust.
Parameters:
- fingerprints (str|list): Key fingerprints to trust
- trustlevel (str): Trust level ('1'=unknown, '2'=never, '3'=marginal,
'4'=full, '5'=ultimate)
Returns:
TrustResult: Result with trust operation status
"""class GenKey(StatusHandler):
type: str # Generated key type
fingerprint: str # Generated key fingerprint
class AddSubkey(StatusHandler):
type: str # Subkey type
fingerprint: str # Subkey fingerprint
class ImportResult(StatusHandler):
count: int # Total keys processed
imported: int # Keys successfully imported
not_imported: int # Keys not imported
unchanged: int # Keys already in keyring
new_user_ids: int # New user IDs added
new_signatures: int # New signatures added
new_subkeys: int # New subkeys added
secret_imported: int # Secret keys imported
secret_unchanged: int # Secret keys unchanged
fingerprints: list # List of processed fingerprints
def summary(self):
"""Return human-readable import summary."""
class ExportResult(StatusHandler):
data: str # Exported key data
class DeleteResult(StatusHandler):
problem_reason: dict # Mapping of problem codes to descriptions
class TrustResult(StatusHandler):
pass
class ListKeys(list):
# List of key dictionaries containing:
# - type: Key type ('pub', 'sec', 'sub', 'ssb')
# - length: Key length in bits
# - algo: Algorithm number
# - keyid: Key ID
# - date: Creation date
# - expires: Expiration date
# - dummy: Dummy key indicator
# - ownertrust: Owner trust level
# - sig_class: Signature class
# - capabilities: Key capabilities
# - issuer: Key issuer
# - flag: Key flags
# - token: Token serial number
# - hash_algo: Hash algorithm
# - curve: Curve name for ECC keys
# - compliance_modes: Compliance mode flags
# - updated: Last updated timestamp
# - origin: Key origin
# - fingerprint: Key fingerprint
# - uids: List of user IDs
# - sigs: List of signatures (if requested)
# - subkeys: List of subkeys
class ScanKeys(ListKeys):
# Same structure as ListKeys but for scanned keys
passimport gnupg
gpg = gnupg.GPG()
# Generate basic RSA key pair
input_data = gpg.gen_key_input(
key_type='RSA',
key_length=2048,
name_real='John Doe',
name_email='john@example.com',
expire_date='2y',
passphrase='secure_passphrase'
)
key = gpg.gen_key(input_data)
print(f"Generated key: {key.fingerprint}")
# Generate ECC key with custom parameters
input_data = gpg.gen_key_input(
key_type='ECDSA',
key_curve='nistp384',
subkey_type='ECDH',
subkey_curve='nistp384',
name_real='Jane Smith',
name_comment='Work Key',
name_email='jane@company.com',
expire_date='1y',
passphrase='work_passphrase'
)
key = gpg.gen_key(input_data)# Import key from ASCII-armored data
key_data = """-----BEGIN PGP PUBLIC KEY BLOCK-----
...
-----END PGP PUBLIC KEY BLOCK-----"""
result = gpg.import_keys(key_data)
print(f"Imported {result.imported} keys")
print(f"Fingerprints: {result.fingerprints}")
# Import from file
result = gpg.import_keys_file('/path/to/keyfile.asc')
# Export public key
exported = gpg.export_keys('john@example.com')
print(exported.data)
# Export secret key with passphrase
exported = gpg.export_keys('john@example.com', secret=True,
passphrase='secure_passphrase')
# Export to file
gpg.export_keys(['key1@example.com', 'key2@example.com'],
output='/path/to/exported_keys.asc')# List all public keys
keys = gpg.list_keys()
for key in keys:
print(f"Key ID: {key['keyid']}")
print(f"Fingerprint: {key['fingerprint']}")
print(f"User IDs: {key['uids']}")
print(f"Length: {key['length']} bits")
# List secret keys
secret_keys = gpg.list_keys(secret=True)
# List specific keys with signatures
specific_keys = gpg.list_keys(keys=['john@example.com'], sigs=True)
# Scan keys from file without importing
scanned = gpg.scan_keys('/path/to/keyfile.asc')
for key in scanned:
print(f"Would import: {key['uids']}")# Delete public key
result = gpg.delete_keys('FINGERPRINT')
print(f"Deletion status: {result.status}")
# Delete secret key (requires confirmation)
result = gpg.delete_keys('FINGERPRINT', secret=True,
passphrase='secure_passphrase')
# Set trust level
result = gpg.trust_keys(['FINGERPRINT1', 'FINGERPRINT2'], '4') # Full trust
# Add subkey to existing key
result = gpg.add_subkey('MASTER_FINGERPRINT',
master_passphrase='master_pass',
algorithm='rsa',
usage='encrypt')
print(f"Added subkey: {result.fingerprint}")Install with Tessl CLI
npx tessl i tessl/pypi-python-gnupg