Skip to content

Instantly share code, notes, and snippets.

@syedrakib
Last active August 3, 2023 18:22
Show Gist options
  • Star 27 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save syedrakib/241b68f5aeaefd7ef8e2 to your computer and use it in GitHub Desktop.
Save syedrakib/241b68f5aeaefd7ef8e2 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
# 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 # 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):
encrypted_msg = publickey.encrypt(a_message, 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, privatekey):
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))
@maxharrison
Copy link

I ran this code but got an error. It is python 3.7 running the latest PyCryptodome
Would you mind helping? I am a little lost...

File "C:(the file location and name but i'm not going to list it).py", line 29
print "%s - (%d)" % (privatekey.exportKey() , len(privatekey.exportKey()))
^
SyntaxError: invalid syntax

@GuusK
Copy link

GuusK commented Aug 15, 2018

@maxharrison These print statements indicate it was written for python 2. It could be easily fixable by making use of the print function instead of the print statement., however, no guarantees.

@anoopsaxena76
Copy link

I am trying to learn this stuff. When I run this, I get the following error.
return (self.key._encrypt(c),) TypeError: argument 1 must be int, not str
I googled and found a bit on b64encode to be imported or encrypt(hash_pass, 32)[0] to include .encode('hex') but to no avail. Can you help?

@bs-sdev
Copy link

bs-sdev commented Sep 18, 2018

Hi @anoopsaxena76,

Just change the encryption line as this:
encrypted_msg = encrypt_message(a_message.encode("utf-8"), publickey)

I just did it myself, it works like a charm

@GavinAren
Copy link

I ran this code but got an error. It is python 3.7 running the latest PyCryptodome

Hey, I'm trying to run this code on Python 3.7 too. What did you change apart from that print statement to adapt the code to Pycrytodome?
I get the error:

File "C:/Users/...(don't want to show this bit)/Gavcoin3.py", line 15, in
from crypto.Hash import SHA
File "C:\Users(don't want to show this bit)\AppData\Local\Programs\Python\Python37\lib\site-packages\crypto\Hash\SHA.py", line 24, in
from Crypto.Hash.SHA1 import doc, new, block_size, digest_size
ModuleNotFoundError: No module named 'Crypto'

Please help!

@tredonet
Copy link

Hi @GavinAren,

I hope you've already solved your issue but if not:
Look in your python directory for /Lib/site-packages/crypto and change it to Crypto. (Capital C)

@ham2qur
Copy link

ham2qur commented Oct 2, 2019

I ran this code but got an error. It is python 3.7 running the latest PyCryptodome

Hey, I'm trying to run this code on Python 3.7 too. What did you change apart from that print statement to adapt the code to Pycrytodome?
I get the error:

File "C:/Users/...(don't want to show this bit)/Gavcoin3.py", line 15, in
from crypto.Hash import SHA
File "C:\Users(don't want to show this bit)\AppData\Local\Programs\Python\Python37\lib\site-packages\crypto\Hash\SHA.py", line 24, in
from Crypto.Hash.SHA1 import doc, new, block_size, digest_size
ModuleNotFoundError: No module named 'Crypto'

Please help!

PyCrypto is written and tested using Python version 2.1 through 3.3. Python
1.5.2 is not supported. My POC resolves that pycrypto is obsoleted in python3.7. Pycryptodome is working alternative of it, but unfortunately it doesn't support plain RSA cryptography.

    def encrypt(self, plaintext, K):
        raise NotImplementedError("Use module Crypto.Cipher.PKCS1_OAEP instead")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment