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.

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):

pip install pycryptodome

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):

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
import binascii

keyPair = RSA.generate(3072)

pubKey = keyPair.publickey()
print(f"Public key:  (n={hex(pubKey.n)}, e={hex(pubKey.e)})")
pubKeyPEM = pubKey.exportKey()
print(pubKeyPEM.decode('ascii'))

print(f"Private key: (n={hex(pubKey.n)}, d={hex(keyPair.d)})")
privKeyPEM = keyPair.exportKey()
print(privKeyPEM.decode('ascii'))

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.

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

Last updated

Was this helpful?