Using OpenPGP in Python via Johnnycanencrypt
April 8, 2022
FOSSASIA
https://github.com/kushaldas/johnnycanencrypt
Licensed under : CC BY-SA 3.0
@kushaldas
@kushaldas
History
- Pretty Good Privacy aka PGP
- 1991 by Phil Zimmermann
- OpenPGP under IETF 1997
- RFC 4880
@kushaldas
- python-gnupg
- gpgme
Existing modules
@kushaldas
@kushaldas
https://pyo3.rs
@kushaldas
How to install?
python3 -m pip install johnnycanencrypt
@kushaldas
import johnnycanencrypt as jce
ks = jce.KeyStore("/home/kdas/code/cards/demo")
k = ks.create_newkey("redhat", ["<cv25519@kushaldas.in>"], jce.Cipher.Cv25519)
with open(f"/home/kdas/code/cards/{k.fingerprint}.pub", 'w') as f:
f.write(k.get_pub_key())
print(k.fingerprint)
Create keys
@kushaldas
with expiry date
edate = datetime.datetime.now() + datetime.timedelta(days=3 * 365)
ks = jce.KeyStore("/home/kdas/code/cards/demo")
k = ks.create_newkey("redhat", ["<cv25519@kushaldas.in>"], jce.Cipher.Cv25519,
expiration=edate, whichkeys=3,
subkeys_expiration=True)
@kushaldas
Import keys
ks = jce.KeyStore("tests/files/store")
ks.import_cert("tests/files/store/public.asc")
@kushaldas
Encrypt/decrypt bytes
public_key = ks.get_key("F51C310E02DC1B7771E176D8A1C5C364EB5B9A20")
encrypted = ks.encrypt(public_key, DATA)
assert encrypted.startswith(b"-----BEGIN PGP MESSAGE-----\n")
secret_key = ks.get_key("F51C310E02DC1B7771E176D8A1C5C364EB5B9A20")
decrypted_text = ks.decrypt(secret_key, encrypted, password="redhat")
.decode("utf-8")
@kushaldas
Encrypt/decrypt file
ks = jce.KeyStore("tests/files/store")
public_key = ks.get_key("F51C310E02DC1B7771E176D8A1C5C364EB5B9A20")
assert ks.encrypt_file(public_key, inputfile, output)
secret_key = ks.get_key("F51C310E02DC1B7771E176D8A1C5C364EB5B9A20")
ks.decrypt_file(secret_key, output, decrypted_output, password="redhat")
@kushaldas
Signing a file
key = ks.get_key("F4F388BBB194925AE301F844C52B42177857DD79")
j = jce.Johnny(_get_cert_data("tests/files/secret.asc"))
tempdir = tempfile.TemporaryDirectory()
output = b"/tmp/sign.asc"
j.sign_file(b"tests/files/text.txt", output, "redhat", False)
@kushaldas
Verify a signature
>>> torkey = ks.import_cert("./kounek7zrdx745qydx6p59t9mqjpuhdf.pub")
>>> torkey
<Key fingerprint=EF6E286DDA85EA2A4BA7DE684E2C6E8793298290 type=PUBLIC>
>>> filepath="./tor-browser-linux64-10.0_en-US.tar.xz"
>>> signaturepath="./tor-browser-linux64-10.0_en-US.tar.xz.asc"
>>> ks.verify_file_detached(torkey, filepath, signaturepath)
True
@kushaldas
@kushaldas
@kushaldas
Let us do some live coding
@kushaldas
@Saptak013
@kushaldas
Usage
https://tumpa.rocks
@kushaldas
@kushaldas
Thank you
jce
By dascommunity
jce
- 636