Skip to content

Instantly share code, notes, and snippets.

@gabrielfalcao
Created November 30, 2019 00:39
Show Gist options
  • Save gabrielfalcao/de82a468e62e73805c59af620904c124 to your computer and use it in GitHub Desktop.
Save gabrielfalcao/de82a468e62e73805c59af620904c124 to your computer and use it in GitHub Desktop.
Using python cryptography module to generate an RSA keypair, serialize, deserialize the keys and perform encryption and decryption
import base64
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
def utf8(s: bytes):
return str(s, 'utf-8')
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=4096,
backend=default_backend()
)
public_key = private_key.public_key()
private_pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
)
with open('private_key.pem', 'wb') as f:
f.write(private_pem)
public_pem = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
with open('public_key.pem', 'wb') as f:
f.write(public_pem)
with open("private_key.pem", "rb") as key_file:
private_key = serialization.load_pem_private_key(
key_file.read(),
password=None,
backend=default_backend()
)
with open("public_key.pem", "rb") as key_file:
public_key = serialization.load_pem_public_key(
key_file.read(),
backend=default_backend()
)
plaintext = b'this is the correct plaintext!'
print(f'plaintext: \033[1;33m{utf8(plaintext)}\033[0m')
encrypted = base64.b64encode(public_key.encrypt(
plaintext,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
))
print(f'encrypted: \033[1;32m{utf8(encrypted)}\033[0m')
decrypted = private_key.decrypt(
base64.b64decode(encrypted),
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
print(f'decrypted: \033[1;31m{utf8(decrypted)}\033[0m')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment