-
-
Save dpjanes/5fa1da35cb35e11840ac86c39c65b719 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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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