DEV Community

Maxime Guilbert
Maxime Guilbert

Posted on • Updated on

How to encode/decode data with a RSA key?

A lot of data is currently on internet and using cloud infrastructures, so if we have private/sensitive datas, we must protect them!

That's why today we will see how to encode/decode data with a RSA key.

What is a RSA key?

A RSA key is a pair of key which allows us to do asymmetric encryption.

Composed of a public and a private key, the first one is used to encode messages which can only be decoded by the second one.


Generate a key

In our example, we will see how to generate a RSA key in Python, but you can generate one using a terminal. Here is a post where I explain how to do it.

Link post - How to generate a SSH RSA key

Setup

Before going forward, we must install pycryptodomex with the following command

pip install pycryptodomex
Enter fullscreen mode Exit fullscreen mode

Code

from Crypto.PublicKey import RSA 

# Generate a RSA key
rsa_key = RSA.generate(2048) 

# Export private and public keys
private_key = rsa_key.exportKey("PEM") 
public_key = rsa_key.publickey().exportKey("PEM") 

# Écriture des clés dans des fichiers
fd = open("private_key.pem", "wb") 
fd.write(private_key) 
fd.close() 

fd = open("public_key.pem", "wb") 
fd.write(public_key) 
fd.close()
Enter fullscreen mode Exit fullscreen mode

As you can see, with pycryptodomex I really easy.


Encode/decode data

Now that we have our keys, we can easily encode and decode data with pycryptodomex.

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

message = b'Test message' 

public_key = RSA.import_key(open('public_key.pem').read()) 
cipher = PKCS1_OAEP.new(public_key) 
ciphertext = cipher.encrypt(message) 
print(ciphertext) 

private_key = RSA.import_key(open('private_key.pem').read()) 
cipher = PKCS1_OAEP.new(private_key) 
decoded_message = cipher.decrypt(ciphertext) 

print(decoded_message.decode("utf-8"))
Enter fullscreen mode Exit fullscreen mode

And if you test the code, you should see the message "Test message" encoded, then full decoded!

So with this, you now know how to encode/decode data with a RSA key!

I hope it will help you! 🍺


You want to support me?

Buy Me A Coffee

Top comments (0)