A wrapper for the Gnu Privacy Guard (GPG or GnuPG)
—
Symmetric and asymmetric encryption/decryption operations supporting multiple data formats and comprehensive configuration options for secure data handling.
Encrypt data using public key cryptography (asymmetric) or symmetric encryption with configurable algorithms and output formats.
def encrypt(self, data, recipients, **kwargs):
"""
Encrypt data for specified recipients.
Parameters:
- data (str): Data to encrypt
- recipients (str|list): Recipient key IDs, fingerprints, or email addresses
- **kwargs: Keyword arguments passed to encrypt_file() including:
- sign (str): Key ID to sign with (creates encrypted and signed message)
- always_trust (bool): Skip key validation
- passphrase (str): Passphrase for signing key
- armor (bool): ASCII-armor the output (default: True)
- symmetric (bool): Use symmetric encryption only
- extra_args (list): Additional GPG arguments
Returns:
Crypt: Result object with encrypted data and status
"""
def encrypt_file(self, fileobj_or_path, recipients, sign=None,
always_trust=False, passphrase=None, armor=True,
output=None, symmetric=False, extra_args=None):
"""
Encrypt a file or file-like object.
Parameters:
- fileobj_or_path (str|file): File path or file-like object to encrypt
- recipients (str|list): Recipient identifiers
- sign (str): Key ID for signing
- always_trust (bool): Skip key validation
- passphrase (str): Passphrase for signing or symmetric encryption
- armor (bool): ASCII-armor the output
- output (str): Output file path
- symmetric (bool): Use symmetric encryption
- extra_args (list): Additional GPG arguments
Returns:
Crypt: Result object with encryption status
"""Decrypt data encrypted with GPG, supporting both asymmetric and symmetric decryption with comprehensive error handling.
def decrypt(self, message, **kwargs):
"""
Decrypt GPG-encrypted data.
Parameters:
- message (str): Encrypted data to decrypt
- always_trust (bool): Skip key validation
- passphrase (str): Passphrase for decryption
- extra_args (list): Additional GPG arguments
Returns:
Crypt: Result object with decrypted data and verification info
"""
def decrypt_file(self, fileobj_or_path, always_trust=False,
passphrase=None, output=None, extra_args=None):
"""
Decrypt an encrypted file or file-like object.
Parameters:
- fileobj_or_path (str|file): File path or file-like object to decrypt
- always_trust (bool): Skip key validation
- passphrase (str): Passphrase for decryption
- output (str): Output file path for decrypted data
- extra_args (list): Additional GPG arguments
Returns:
Crypt: Result object with decryption status
"""Analyze encrypted messages to determine recipient information without decrypting the content.
def get_recipients(self, message, **kwargs):
"""
Get recipient information from encrypted data.
Parameters:
- message (str): Encrypted data to analyze
- **kwargs: Additional arguments passed to get_recipients_file()
Returns:
Crypt: Result with recipient information
"""
def get_recipients_file(self, fileobj_or_path, extra_args=None):
"""
Get recipient information from encrypted file.
Parameters:
- fileobj_or_path (str|file): Encrypted file to analyze
- extra_args (list): Additional GPG arguments
Returns:
Crypt: Result with recipient information
"""class Crypt(StatusHandler):
ok: bool # True if operation succeeded
status: str # Operation status message
stderr: str # Error output from GPG
data: str # Encrypted/decrypted data
# Verification information (for decrypt operations)
valid: bool # True if signature is valid (decrypt + verify)
fingerprint: str # Signer's fingerprint (if signed)
username: str # Signer's username (if signed)
trust_level: int # Trust level of signing key
trust_text: str # Human-readable trust level
signature_id: str # Signature ID
creation_date: str # Signature creation date
# Recipients information (for get_recipients operations)
recipients: list # List of recipient key informationimport gnupg
gpg = gnupg.GPG()
# Encrypt data for single recipient
plaintext = "This is sensitive information"
encrypted = gpg.encrypt(plaintext, recipients=['alice@example.com'])
if encrypted.ok:
print("Encryption successful")
print(str(encrypted)) # ASCII-armored encrypted data
else:
print(f"Encryption failed: {encrypted.status}")
# Decrypt the data
decrypted = gpg.decrypt(str(encrypted), passphrase='alice_passphrase')
if decrypted.ok:
print("Decryption successful")
print(str(decrypted)) # Original plaintext
else:
print(f"Decryption failed: {decrypted.status}")# Encrypt for multiple recipients
recipients = [
'alice@example.com',
'bob@example.com',
'DEADBEEFCAFEBABE12345678' # Key fingerprint
]
encrypted = gpg.encrypt(plaintext, recipients=recipients, armor=True)
# Any of the recipients can decrypt
decrypted_by_alice = gpg.decrypt(str(encrypted), passphrase='alice_pass')
decrypted_by_bob = gpg.decrypt(str(encrypted), passphrase='bob_pass')# Encrypt with passphrase only (no public key needed)
encrypted = gpg.encrypt(
"Secret data",
recipients=None, # No recipients for symmetric
symmetric=True,
passphrase='shared_secret',
cipher_algo='AES256'
)
# Decrypt with the same passphrase
decrypted = gpg.decrypt(str(encrypted), passphrase='shared_secret')# Encrypt a file
result = gpg.encrypt_file(
'/path/to/document.pdf',
recipients=['recipient@example.com'],
output='/path/to/document.pdf.gpg',
armor=False # Binary output
)
if result.ok:
print("File encrypted successfully")
# Decrypt a file
result = gpg.decrypt_file(
'/path/to/document.pdf.gpg',
passphrase='recipient_passphrase',
output='/path/to/decrypted_document.pdf'
)# Encrypt and sign in one operation
encrypted_and_signed = gpg.encrypt(
"Important message",
recipients=['recipient@example.com'],
sign='sender@example.com', # Sign with this key
passphrase='sender_passphrase'
)
# Decrypt and verify signature
decrypted = gpg.decrypt(str(encrypted_and_signed),
passphrase='recipient_passphrase')
if decrypted.ok:
print(f"Decrypted: {str(decrypted)}")
if decrypted.valid:
print(f"Valid signature from: {decrypted.username}")
print(f"Fingerprint: {decrypted.fingerprint}")
print(f"Trust level: {decrypted.trust_text}")
else:
print("Invalid or no signature")# Encrypt with custom algorithms and compression
encrypted = gpg.encrypt(
"Data to encrypt",
recipients=['user@example.com'],
cipher_algo='AES256', # Strong encryption
digest_algo='SHA512', # Strong hash
compress_algo='BZIP2', # Better compression
extra_args=['--verbose'] # Additional GPG options
)
# Encrypt always trusting keys (skip validation)
encrypted = gpg.encrypt(
"Urgent message",
recipients=['new_key@example.com'],
always_trust=True # Skip key validation
)# Analyze encrypted message to see recipients
encrypted_data = """-----BEGIN PGP MESSAGE-----
...
-----END PGP MESSAGE-----"""
recipients_info = gpg.get_recipients(encrypted_data)
if recipients_info.ok:
print("Message encrypted for:")
for recipient in recipients_info.recipients:
print(f" - Key ID: {recipient}")
# Analyze encrypted file
recipients_info = gpg.get_recipients_file('/path/to/encrypted.gpg')# Comprehensive error handling
def safe_encrypt(gpg_instance, data, recipients, **kwargs):
try:
result = gpg_instance.encrypt(data, recipients, **kwargs)
if result.ok:
return str(result)
else:
print(f"Encryption failed: {result.status}")
if result.stderr:
print(f"GPG stderr: {result.stderr}")
return None
except Exception as e:
print(f"Exception during encryption: {e}")
return None
# Safe decryption with retry logic
def safe_decrypt(gpg_instance, encrypted_data, passphrases):
for passphrase in passphrases:
try:
result = gpg_instance.decrypt(encrypted_data, passphrase=passphrase)
if result.ok:
return str(result)
except Exception as e:
print(f"Decryption attempt failed: {e}")
continue
print("All decryption attempts failed")
return NoneInstall with Tessl CLI
npx tessl i tessl/pypi-python-gnupg