Rsa Key Generation Example Python

An example of asymmetric encryption in python using a public/private keypair - utilizes RSA from PyCrypto library

Oct 15, 2016  Generating RSA keys with Python 3 Posted on October 15, 2016 by Guy Bowerman I was looking for a quick way to generate an RSA key in Python 3 for some unit tests which needed a public key as an OpenSSH string. Proj RSA2: Cracking a Short RSA Key (15 pts.) What you need: A Mac or Linux computer with Python. Purpose To break into RSA encryption without prior knowledge of the private key. This is only possible for small RSA keys, which is why RSA keys should be long for security. Summary Here's a diagram from the textbook showing the RSA calculations.

RSA_example.py
# 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/
fromCryptoimportRandom
fromCrypto.PublicKeyimportRSA
importbase64
defgenerate_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()
returnprivatekey, publickey
defencrypt_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
returnencoded_encrypted_msg
defdecrypt_message(encoded_encrypted_msg, privatekey):
decoded_encrypted_msg=base64.b64decode(encoded_encrypted_msg)
decoded_decrypted_msg=privatekey.decrypt(decoded_encrypted_msg)
returndecoded_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))

Below is an example in Python that uses the rsa library. Because RSA is so ubiquitous, you should be able to easily port this to another language if required. First, create an RSA key pair on your development machine. We use 512 bits here because it leads to shorter signatures. In practice, you probably want 2048 bits or more. There are other methods to generate primes (e.g., do step 1, if step 2 fails goto step 1). The method I outlined is what OpenSSL uses though. For an official, public standard on RSA key generation, see FIPS 186-4, section 5.1 and Appendix B.3.1. RSA Encrypt / Decrypt - Examples. Now let's demonstrate how the RSA algorithms works by a simple example in Python.The below code will generate random RSA key-pair, will encrypt a short message and will decrypt it back to its original form, using the RSA-OAEP padding scheme.

Rsa Key Generation Example Python

commented Aug 11, 2018

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

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.

Rsa Public Key Example

commented Aug 31, 2018

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?

commented Sep 18, 2018
edited

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

Rsa Key Generation Algorithm

commented Aug 28, 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)AppDataLocalProgramsPythonPython37libsite-packagescryptoHashSHA.py', line 24, in
from Crypto.Hash.SHA1 import doc, new, block_size, digest_size
ModuleNotFoundError: No module named 'Crypto'

Please help!

commented Sep 13, 2019

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)

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)AppDataLocalProgramsPythonPython37libsite-packagescryptoHashSHA.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.

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

Now let's demonstrate how the RSA algorithms works by a simple example in Python. The below code will generate random RSA key-pair, will encrypt a short message and will decrypt it back to its original form, using the RSA-OAEP padding scheme.

First, install the pycryptodome package, which is a powerful Python library of low-level cryptographic primitives (hashes, MAC codes, key-derivation, symmetric and asymmetric ciphers, digital signatures):

RSA Key Generation

Now, let's write the Python code. First, generate the RSA keys (1024-bit) and print them on the console (as hex numbers and in the PKCS#8 PEM ASN.1 format):

Run the above code example: https://repl.it/@nakov/RSA-Key-Generation-in-Python.

We use short key length to keep the sample input short, but in a real world scenario it is recommended to use 3072-bit or 4096-bit keys.

RSA Encryption

Next, encrypt the message using RSA-OAEP encryption scheme (RSA with PKCS#1 OAEP padding) with the RSA public key:

Run the above code example: https://repl.it/@nakov/RSA-encryption-in-Python.

RSA Decryption

Finally, decrypt the message using using RSA-OAEP with the RSA private key:

Run the above code example: https://repl.it/@nakov/RSA-decryption-in-Python.

Sample Output

A sample output of the code execution for the entire example is given below:

Notes:

  • If you run the above example, your output will be different, because it generates different random RSA key-pair at each execution.
  • Even if you encrypt the same message several times with the same public key, you will get different output. This is because the OAEP padding algorithm injects some randomness with the padding.
  • If you try to encrypt larger messages, you will get and exception, because the 1024-bit key limits the maximum message length.

Rsa Key Generation Python

Now play with the above code, modify it and run it to learn how RSA works in action.