Skip to content

Instantly share code, notes, and snippets.

@btoueg
Last active January 21, 2019 13:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save btoueg/5a81bbc8a2b21c5a8a6a0bbaeb6906b7 to your computer and use it in GitHub Desktop.
Save btoueg/5a81bbc8a2b21c5a8a6a0bbaeb6906b7 to your computer and use it in GitHub Desktop.
An example of asymmetric encryption in python 2.7 - utilizes cryptography library
# -*- encoding: utf-8 -*-
import base64
import logging
from cryptography.exceptions import UnsupportedAlgorithm
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.asymmetric import rsa
# set up logger
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def demonstrate_asymmetric_string_encryption(plain_text):
"""
Example for asymmetric encryption and decryption of a string in one method.
- Generation of public and private RSA 4096 bit keypair
- RSA encryption and decryption of text using OAEP and MGF1 padding
- BASE64 encoding as representation for the byte-arrays
- UTF-8 encoding of Strings
- Exception handling
"""
try:
private_key_path = "./id_rsa"
try:
with open(private_key_path, "rb") as key_file:
private_key = serialization.load_pem_private_key(
key_file.read(), password=None, backend=default_backend()
)
except IOError:
# GENERATE PRIVATE KEY
private_key = rsa.generate_private_key(
public_exponent=65537, key_size=4096, backend=default_backend()
)
# SAVE PRIVATE KEY
pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption(),
)
with open(private_key_path, "wb") as g:
g.write(pem)
public_key = private_key.public_key()
# ENCRYPTION
cipher_text_bytes = public_key.encrypt(
plaintext=plain_text.encode("utf-8"),
padding=padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA512(),
label=None,
),
)
# CONVERSION of raw bytes to BASE64 representation
cipher_text = base64.urlsafe_b64encode(cipher_text_bytes)
# DECRYPTION
decrypted_cipher_text_bytes = private_key.decrypt(
ciphertext=base64.urlsafe_b64decode(cipher_text),
padding=padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA512(),
label=None,
),
)
decrypted_cipher_text = decrypted_cipher_text_bytes.decode("utf-8")
logger.info(
"Decrypted and original plain text are the same: %s",
decrypted_cipher_text == plain_text,
)
except UnsupportedAlgorithm:
logger.exception("Asymmetric encryption failed")
if __name__ == "__main__":
import json
# demonstrate method
demonstrate_asymmetric_string_encryption(
json.dumps(
{u"type": u"example of json that could be symmetrically encrypted 😀 "}
).encode("utf-8")
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment