Skip to content

Instantly share code, notes, and snippets.

@salexkidd
Created April 14, 2019 13:53
Show Gist options
  • Save salexkidd/703f8d79cdb3b0182b1945d4248c8bb7 to your computer and use it in GitHub Desktop.
Save salexkidd/703f8d79cdb3b0182b1945d4248c8bb7 to your computer and use it in GitHub Desktop.
Public key encryption with cryptography
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.asymmetric import padding
from cryptography.hazmat.primitives import hashes
# Create Private Key
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend()
)
private_key_str = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
).decode("utf-8")
public_key_str = private_key.public_key().public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
).decode("utf-8")
print("=========================== PRIVATE KEY ===========================")
print(private_key_str)
print("=========================== PUBLIC KEY ===========================")
print(public_key_str)
del(private_key)
# Load Public Key & Public key
public_key = serialization.load_pem_public_key(
public_key_str.encode("utf-8"),
backend=default_backend()
)
private_key = serialization.load_pem_private_key(
private_key_str.encode("utf-8"),
backend=default_backend(),
password=None,
)
# Ciper & b64
cipher_bytes = public_key.encrypt(
"All your base are belong to us".encode('utf-8'),
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None,
)
)
b64_ciphertext = base64.b64encode(cipher_bytes)
del(cipher_bytes)
cipher_bytes = base64.b64decode(b64_ciphertext)
plaintext = private_key.decrypt(
cipher_bytes,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
print("=" * 79)
print(cipher_bytes)
print("-" * 79)
print(plaintext.decode("utf-8"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment