Skip to content

Instantly share code, notes, and snippets.

@amfg
Created June 29, 2016 22:43
Show Gist options
  • Save amfg/643b03b87d076836abe297cb87701bdb to your computer and use it in GitHub Desktop.
Save amfg/643b03b87d076836abe297cb87701bdb to your computer and use it in GitHub Desktop.
PGPy usage
#!/usr/bin/python3.4
# requires pgpy >=0.4.0 (latest, as of 06/30/2016)
import pgpy
from pgpy.constants import PubKeyAlgorithm, KeyFlags, HashAlgorithm, SymmetricKeyAlgorithm, CompressionAlgorithm
class Encryption:
@staticmethod
def get_key(name, plain=False):
try:
key = pgpy.PGPKey.from_file('{}.asc'.format(name))[0]
return str(key) if plain else key
except:
return None
@staticmethod
def generate_certificates():
"""
Will create two PGP pairs inside current folder. one named first.asc, second one second.asc
NAME will be used as name of the owner.
Both private (key) and public (key.pubkey) keys will be stored in each file.
"""
NAME = "Tester"
for pair_name in ['first', 'second']:
key = pgpy.PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 4096)
uid = pgpy.PGPUID.new(NAME)
key.add_uid(uid,
usage={KeyFlags.Sign, KeyFlags.EncryptCommunications, KeyFlags.EncryptStorage},
hashes=[HashAlgorithm.SHA512],
ciphers=[PubKeyAlgorithm.RSAEncryptOrSign, SymmetricKeyAlgorithm.AES256],
compression=[CompressionAlgorithm.ZLIB, CompressionAlgorithm.BZ2, CompressionAlgorithm.ZIP, CompressionAlgorithm.Uncompressed])
open('{}.asc'.format(pair_name), 'wb').write(bytes(key))
@staticmethod
def encrypt(data, key='first'):
k = Encryption.get_key(key)
m = k.pubkey.encrypt(pgpy.PGPMessage.new(data), cipher=SymmetricKeyAlgorithm.AES256)
return bytes(m)
@staticmethod
def decrypt(data, key='first'):
k = Encryption.get_key(key)
m = k.decrypt(pgpy.PGPMessage.from_blob(data))
return bytes(m._message.contents) if isinstance(m._message.contents, bytearray) else m._message.contents
if __name__ == '__main__':
import os
if not os.path.isfile("first.asc"):
# generate keys first
Encryption.generate_certificates()
""" sanity test """
message = "Just testing something, never mind me..."
encrypted = Encryption.encrypt(message) # use first.asc for encryption
decrypted = Encryption.decrypt(encrypted) # use first.asc for decryption
if message == decrypted:
print('Decryption using the same key successful.')
try:
failed_decryption = Encryption.decrypt(encrypted, "second") # use second.asc, this will fail
except pgpy.errors.PGPError:
print('Decryption using different keys failed, as expected!')
""" also supports bytes """
import os
message = os.urandom(64)
encrypted = Encryption.encrypt(message, "second") # just for fun, use second instead of first
decrypted = Encryption.decrypt(encrypted, "second") # same behaviour
if message == decrypted:
print('Decryption using the same key successful.')
try:
failed_decryption = Encryption.decrypt(encrypted) # use first.asc, this will fail
except pgpy.errors.PGPError:
print('Decryption using different keys failed, as expected!')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment