Skip to content

Instantly share code, notes, and snippets.

@tzaffi
Last active September 23, 2021 19:11
Show Gist options
  • Save tzaffi/8b3c103042bc3a9815efa5dc60779317 to your computer and use it in GitHub Desktop.
Save tzaffi/8b3c103042bc3a9815efa5dc60779317 to your computer and use it in GitHub Desktop.
PGPy - creating keys, encrypting and decrypting
from pgpy import PGPUID, PGPKey, PGPMessage
from pgpy.constants import (
PubKeyAlgorithm,
KeyFlags,
HashAlgorithm,
SymmetricKeyAlgorithm,
CompressionAlgorithm,
)
# 1. Recipient sets up user, and generates a key for that user
uid = PGPUID.new("Abraham Lincoln", comment="Honest Abe", email="abraham.lincoln@whitehouse.gov")
key = PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 4096)
key.add_uid(
uid,
usage={KeyFlags.Sign, KeyFlags.EncryptCommunications, KeyFlags.EncryptStorage},
hashes=[HashAlgorithm.SHA256, HashAlgorithm.SHA384, HashAlgorithm.SHA512, HashAlgorithm.SHA224],
ciphers=[SymmetricKeyAlgorithm.AES256, SymmetricKeyAlgorithm.AES192, SymmetricKeyAlgorithm.AES128],
compression=[
CompressionAlgorithm.ZLIB,
CompressionAlgorithm.BZ2,
CompressionAlgorithm.ZIP,
CompressionAlgorithm.Uncompressed,
],
)
# Typically, recipient then saves the key information to a file on their server
# 2. Recipient publishes the public key.
print(f"public key:\n{key.pubkey}")
# 3. Sender retrieves pubkey.
# Here we use `from_blob`. But typically you'd use `from_file`:
pubkey, _ = PGPKey.from_blob(str(key.pubkey))
# 4. Sender prepares a message
message = PGPMessage.new("Hello PGP! You're so Clever!!!!")
print(f"plaintext: [{message.message}]")
# 5. Sender encrypts the message using the public key
ciphertext = str(pubkey.encrypt(message))
print(f"cipherbytes: [{ciphertext}]")
# 6. Sender sends the ciphertext
# ...
# key below would typically be reconstructed from its saved file
# 7. Recipient decrypts the cyphertext
cipher_msg = PGPMessage.from_blob(ciphertext)
decrypted = key.decrypt(cipher_msg).message
print(f"decrypted: [{decrypted}]")
assert decrypted == message.message
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment