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