Skip to content

Instantly share code, notes, and snippets.

@bertrand-caron
Forked from syedrakib/RSA_example.py
Last active June 6, 2018 03:17
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 bertrand-caron/b565b5fe74e74e3748d6f3f95aba87d3 to your computer and use it in GitHub Desktop.
Save bertrand-caron/b565b5fe74e74e3748d6f3f95aba87d3 to your computer and use it in GitHub Desktop.
An example of asymmetric encryption in python using a public/private keypair - utilizes RSA from PyCrypto library and Python3.5
# Inspired from http://coding4streetcred.com/blog/post/Asymmetric-Encryption-Revisited-(in-PyCrypto)
# PyCrypto docs available at https://www.dlitz.net/software/pycrypto/api/2.6/
from Crypto import Random
from Crypto.PublicKey import RSA
import base64
def generate_keys():
# RSA modulus length must be a multiple of 256 and >= 1024
modulus_length = 256 * 4 * 4 # use larger value in production
privatekey = RSA.generate(modulus_length, Random.new().read)
publickey = privatekey.publickey()
return (privatekey, publickey)
def encrypt_message(a_message, publickey: str) -> bytes:
encrypted_msg = publickey.encrypt(a_message.encode(), 32)[0]
encoded_encrypted_msg = base64.b64encode(encrypted_msg) # base64 encoded strings are database friendly
return encoded_encrypted_msg
def decrypt_message(encoded_encrypted_msg: bytes, privatekey: str) -> str:
decoded_encrypted_msg = base64.b64decode(encoded_encrypted_msg)
decoded_decrypted_msg = privatekey.decrypt(decoded_encrypted_msg)
return decoded_decrypted_msg
########## BEGIN ##########
a_message = "The quick brown fox jumped over the lazy dog"
privatekey, publickey = generate_keys()
encrypted_msg = encrypt_message(a_message, publickey)
decrypted_msg = decrypt_message(encrypted_msg, privatekey)
print("%s - (%d)" % (privatekey.exportKey() , len(privatekey.exportKey())))
print("%s - (%d)" % (publickey.exportKey() , len(publickey.exportKey())))
print(" Original content: %s - (%d)" % (a_message, len(a_message)))
print("Encrypted message: %s - (%d)" % (encrypted_msg, len(encrypted_msg)))
print("Decrypted message: %s - (%d)" % (decrypted_msg, len(decrypted_msg)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment