Created
April 23, 2020 07:14
-
-
Save arahmanali/910ecdd7bfd36dd6759448aa7e8881d2 to your computer and use it in GitHub Desktop.
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
# package used in this gist: pyca/cryptography | |
# Step 1: Generating a key | |
from cryptography.hazmat.backends import default_backend | |
from cryptography.hazmat.primitives.asymmetric import rsa | |
private_key = rsa.generate_private_key( | |
public_exponent=65537, | |
key_size=2048, | |
backend=default_backend() | |
) | |
public_key = private_key.public_key() | |
# Step 2: Storing the keys | |
from cryptography.hazmat.primitives import serialization | |
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(pem) | |
pem = public_key.public_bytes( | |
encoding=serialization.Encoding.PEM, | |
format=serialization.PublicFormat.SubjectPublicKeyInfo | |
) | |
with open('public_key.pem', 'wb') as f: | |
f.write(pem) | |
# Step 3: Reading the keys back in (for demonstration purposes) | |
from cryptography.hazmat.backends import default_backend | |
from cryptography.hazmat.primitives import serialization | |
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() | |
) | |
# Step 4: Encrypting and decrypting | |
from cryptography.hazmat.primitives import hashes | |
from cryptography.hazmat.primitives.asymmetric import padding | |
message = b'encrypt me!' | |
encrypted = public_key.encrypt( | |
message, | |
padding.OAEP( | |
mgf=padding.MGF1(algorithm=hashes.SHA256()), | |
algorithm=hashes.SHA256(), | |
label=None | |
) | |
) | |
original_message = private_key.decrypt( | |
encrypted, | |
padding.OAEP( | |
mgf=padding.MGF1(algorithm=hashes.SHA256()), | |
algorithm=hashes.SHA256(), | |
label=None | |
) | |
) | |
# Checking the results | |
print(original_message) | |
# Result: b'encrypt me!' | |
print(message == original_message) | |
# Result: True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment