PGPy - Pretty Good Privacy for Python

0.6.0 · active · verified Thu Apr 09

PGPy is a Python library that implements Pretty Good Privacy (PGP) as described in RFC 4880. It provides capabilities for key generation, encryption, decryption, and signature management. The library is currently at version 0.6.0 and has an irregular release cadence, with major changes often accompanied by Python version requirement updates.

Warnings

Install

Imports

Quickstart

Demonstrates generating a new PGP key, adding a User ID, optionally protecting the private key with a passphrase, encrypting a simple message, and then decrypting it. This covers the fundamental use cases for PGPy.

import pgpy
from pgpy.constants import PubKeyAlgorithm, KeyFlags, HashAlgorithm, SymmetricKeyAlgorithm, CompressionAlgorithm

# 1. Generate a new RSA PGP key
key = pgpy.PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 4096)

# 2. Create a User ID
uid = pgpy.PGPUID.new('Test User', comment='example', email='test@example.com')

# 3. Add the User ID to the key, defining its capabilities
key.add_uid(uid,
            usage={KeyFlags.Sign, KeyFlags.Encrypt},
            hashes=[HashAlgorithm.SHA512, HashAlgorithm.SHA256],
            ciphers=[SymmetricKeyAlgorithm.AES256, SymmetricKeyAlgorithm.AES192, SymmetricKeyAlgorithm.AES128],
            compression=[CompressionAlgorithm.ZLIB, CompressionAlgorithm.BZ2, CompressionAlgorithm.ZIP, CompressionAlgorithm.Uncompressed])

# 4. (Optional) Protect the private key with a passphrase
passphrase = "my_secret_passphrase"
key.protect(passphrase, SymmetricKeyAlgorithm.AES256, HashAlgorithm.SHA256)

# 5. Create a PGP message
message_to_encrypt = pgpy.PGPMessage.new("This is a secret message that needs to be encrypted.")

# 6. Encrypt the message using the public key part of the generated key
encrypted_message = key.encrypt(message_to_encrypt)

# 7. Decrypt the message using the private key part
# If the key is protected, it must be unlocked first.
if key.is_protected:
    with key.unlock(passphrase):
        decrypted_message = key.decrypt(encrypted_message)
else:
    decrypted_message = key.decrypt(encrypted_message)

print(f"Original message: {message_to_encrypt.message}")
print(f"Decrypted message: {decrypted_message.message}")

# You can also export the key to an armored string
# public_key_armor = str(key.pubkey)
# private_key_armor = str(key) # WARNING: Handle private keys with extreme care!

view raw JSON →