Implementing RSA Encryption and Decryption in Python (2024)

Data encryption is an important practice used to protect data transfer on the internet. This helps prevent data sent on the internet from unauthorized access.

One of the major algorithms used for data protection on the internet is the Rivest, Shamir, and Adleman (RSA algorithm), named after the inventors of this encryption and decryption algorithm.

RSA is a public key algorithm widely used for secure data transmission. This is one of the major cyber security methods of data protection.

In this tutorial, we will discuss the working of the RSA algorithm and how this algorithm can be implemented in Python.

Table of contents

  • Table of contents
  • Prerequisites
  • How the RSA encryption and decryption works
  • Implementing the RSA algorithm in Python
  • Conclusion

Prerequisites

To follow along with this tutorial, you need to have:

I will be using Visual Studio Code for this tutorial.

How the RSA encryption and decryption works

Each pair of the RSA algorithm has two keys, i.e. a public key and a private key. One key is used for encrypting the message which can only be decrypted by the other key.

For instance, let’s say we have two peers communicating with each other in a channel secured by the RSA algorithm. The sender will encrypt the plain text with the recipient’s public key. This is so that the receiver is the only one who can decrypt the message using their private key.

The public key will be available in a public key repository. However, for the private key, as the name suggests, it is kept private at the recipient’s side.

Implementing the RSA algorithm in Python

In this tutorial, we will be using rsa python package. Open your terminal and use the command below to install it:

pip install rsa

Once the package is downloaded, the first thing we need to do is to import rsa into our program:

import rsa

We will start by implementing two helper methods to generate the private and public keys. The keys will be a tuple of public and private keys, and then write the keys into files.

To write the keys into the files, we will create a folder named Keys in our project folder. The Keys folder will have two files for holding private and public keys; one key in each file.

We will implement this using the code below:

def generateKeys(): (publicKey, privateKey) = rsa.newkeys(1024) with open('keys/publcKey.pem', 'wb') as p: p.write(publicKey.save_pkcs1('PEM')) with open('keys/privateKey.pem', 'wb') as p: p.write(privateKey.save_pkcs1('PEM'))

Now that we have saved the keys in our files, the next thing we need to do is to load the keys.

To load the keys, we will use the code snippet below that opens the files that we created above, and return both the private and public keys:

def loadKeys(): with open('keys/publicKey.pem', 'rb') as p: publicKey = rsa.PublicKey.load_pkcs1(p.read()) with open('keys/privateKey.pem', 'rb') as p: privateKey = rsa.PrivateKey.load_pkcs1(p.read()) return privateKey, publicKey

Next, create two other methods to encrypt and decrypt our message.

Start by creating the encryption method using the code below. The encrypt method will take the message and the encryption key.

After defining the encrypt method, we need to return the encrypted message. We will encode the message in ASCII and give it the key:

def encrypt(message, key): return rsa.encrypt(message.encode('ascii'), key)

Let us now create the decryption method. This method will take the ciphertext and the key to decrypt. What we will do is to try and decrypt the message and return the decrypted message.

Since we used the ASCII encoding, we will use ASCII decoding as well.

If this fails, it means that the key was not able to decrypt the message, so what we will do is return false. We will use the code below to implement the decryption method.

def decrypt(ciphertext, key): try: return rsa.decrypt(ciphertext, key).decode('ascii') except: return False

Finally, we will create two methods to sign and verify our message with a key using the sha1 hash function. This method will take the message and the key so that we sign our message with a key.

The message that we will encode will be given the key and our hashing algorithm. In this case, SHA-1.

The sign method is implemented using the code below:

def sign(message, key): return rsa.sign(message.encode('ascii'), key, 'SHA-1')

For the verification of the message, we will create the verify method and pass in the message, the signature to verify, and the key. So, what we need to do is to try to verify our message.

This verify method returns the hash algorithm used in the signature. So, what we do is to check that this is equal to the hash algorithm, i.e; SHA-1.

If the signature is authentic, then it returns true. In case there is an exception, it will return false which means that the verification has failed. This means either the message or the signature were manipulated and are not authentic.

def verify(message, signature, key): try: return rsa.verify(message.encode('ascii'), signature, key,) == 'SHA-1' except: return False

Now that we have the RSA algorithm, we will create our program. We will start by generating our keys.

We will call the generate keys method, load the public and private keys as implemented in the code below:

generateKeys()publicKey, privateKey =load_keys()

We will then take the message input from the user, and encrypt the message using the public key. This represents the sender of the message:

message = input('Write your message here:')ciphertext = encrypt(message, publicKey)

Now that we have the ciphertext, we will generate the signatures using the code below to sign the message with our private key. This enables the sender to verify the message with the public key and determine if the message is authentic:

signature = sign(message, privateKey)

Next, we will decrypt our encrypted message to have plain text. To implement this, we will create a decryption method and pass it in the ciphertext and the private key as shown below:

text = decrypt(ciphertext, privateKey)

After getting our plain text, the next thing to do is to print out the ciphertext and the signature.

print(f'Cipher text: {ciphertext}')print(f'Signature: {signature}')

We will check the plain text in the next step. If it is plain text, then we indicate message was successfully decrypted otherwise, unable to decrypt the message:

if text: print(f'Message text: {text}')else: print(f'Unable to decrypt the message.')

We verify our signature using the code below:

if verify(text, signature, publicKey): print(Successfully verified signature)else: print('The message signature could not be verified')

With that, you can enter your message, encrypt, and then decrypt it.

Conclusion

In this tutorial, we have encrypted a message using a public key and signed it using our private key.

If you have two peers; i.e, peer A talking to peer B. When peer A is sending a message to peer B, the message should be encrypted using the public key of peer B. However, this method is signed using the private key of peer A, which is the peer sending the message.

On the recipient’s side, which is peer B, it is going to decrypt the message using the private key and then verify the signature of the message using the public key of peer A which is the sender of the message.

However, this is not the case in this tutorial since we don’t have the sender or the receiver of the message, hence we are getting the knowledge on the use of a signature, signing a message, and verifying the signature.

Peer Review Contributions by: Dawe Daniel

Implementing RSA Encryption and Decryption in Python (2024)

FAQs

How to encrypt and decrypt with RSA Python? ›

Steps:
  1. Import rsa library.
  2. Generate public and private keys with rsa. ...
  3. Encode the string to byte string.
  4. Then encrypt the byte string with the public key.
  5. Then the encrypted string can be decrypted with the private key.
  6. The public key can only be used for encryption and the private can only be used for decryption.
Jun 8, 2022

How to implement RSA encryption in Python? ›

Implementing the RSA algorithm in Python
  1. def generateKeys(): (publicKey, privateKey) = rsa. ...
  2. def loadKeys(): with open('keys/publicKey.pem', 'rb') as p: publicKey = rsa. ...
  3. def encrypt(message, key): return rsa. ...
  4. def decrypt(ciphertext, key): try: return rsa. ...
  5. def sign(message, key): return rsa.
Jan 28, 2022

Why is it so difficult to unencrypt RSA encryption? ›

There are infinitely many prime numbers. Using a computer, it is relatively easy to find lots of large prime numbers. At present, however, it is very difficult to find the prime factorisation of a very large number. This is what makes RSA encryption so hard to crack.

How to do encryption and decryption in Python? ›

To encrypt and decrypt a Python string, install and import the cryptography library, generate a Fernet key, and create a Fernet object with it. You can then encrypt the string using the Fernet. encrypt() method and decrypt the encrypted string using the Fernet. decrypt() method.

Is RSA easy to decrypt? ›

Messages can be encrypted by anyone, via the public key, but can only be decoded by someone who knows the prime numbers. The security of RSA relies on the practical difficulty of factoring the product of two large prime numbers, the "factoring problem". Breaking RSA encryption is known as the RSA problem.

What is RSA algorithm in Python? ›

The RSA algorithm is a widely used public-key encryption algorithm named after its inventors Ron Rivest, Adi Shamir, and Leonard Adleman. It is based on the mathematical concepts of prime factorization and modular arithmetic.

What is RSA module in Python? ›

Python-RSA is a pure-Python RSA implementation. It supports encryption and decryption, signing and verifying signatures, and key generation according to PKCS#1 version 1.5. It can be used as a Python library as well as on the commandline. The code was mostly written by Sybren A.

What are two 2 possible attacks against RSA encryption? ›

Security of RSA
  • Short message attack: In this we assume that attacker knows some blocks of plain text and tries to decode cipher text with the help of that. ...
  • Cycling attack: In this attack, the attacker thinks that the cipher text has been generated by using some permutation. ...
  • Unconcealed Message attack:
Feb 13, 2023

Is RSA hackable? ›

Ten years later, the RSA hack is still considered to be among the worst cybersecurity breaches to date. It started with phishing emails to two employees which contained malware.

What is the hardest encryption to decrypt? ›

AES 256-bit encryption is the strongest and most robust encryption standard that is commercially available today. While it is theoretically true that AES 256-bit encryption is harder to crack than AES 128-bit encryption, AES 128-bit encryption has never been cracked.

Can Python be used for encryption? ›

There are many encryption algorithms available in python, but not all of them are equally secure or suitable for your needs. Some of the most common and widely used algorithms are AES, RSA, and Fernet.

How do I encrypt credentials in Python? ›

There are various Python modules that are used to hide the user's inputted password, among them one is maskpass() module. In Python with the help of maskpass() module and base64() module we can hide the password of users with asterisk(*) during input time and then with the help of base64() module it can be encrypted.

How to perform encryption and decryption using RSA algorithm? ›

Step 1: In the first step, select two large prime numbers, p and q. Step 2: Multiply these numbers to find n = p x q, where n is called the modulus for encryption and decryption. Step 3: If n = p x q, then the public key is <e, n>. A plaintext message m is encrypted using public key <e, n>.

How to encrypt RSA encryption? ›

How Do You Create RSA Encryption
  1. First convert your plaintext message from an ASCII string into an array of bytes.
  2. Then, convert the byte array into a large integer.
  3. Using the public key created using the RSA algorithm, create a Cypher text to be sent to the recipient.
May 8, 2023

How do I decrypt an encrypted RSA key? ›

How to Decrypt an RSA Private Key Using OpenSSL
  1. Open terminal.
  2. Run the open ssl command to decrypt the file $ openssl rsa -in <encrypted_private.key> -out <decrypted_private.key> Enter pass phrase for encrypted_private.key: <enter the password> writing RSA key.
Feb 22, 2021

How to decrypt RSA certificate? ›

Enter encryption key e and plaintext message M in the table on the left, then click the Encrypt button. The encrypted message appears in the lower box. To decrypt a message, enter valid modulus N below. Enter decryption key d and encrypted message C in the table on the right, then click the Decrypt button.

Top Articles
Latest Posts
Article information

Author: Sen. Emmett Berge

Last Updated:

Views: 6515

Rating: 5 / 5 (60 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Sen. Emmett Berge

Birthday: 1993-06-17

Address: 787 Elvis Divide, Port Brice, OH 24507-6802

Phone: +9779049645255

Job: Senior Healthcare Specialist

Hobby: Cycling, Model building, Kitesurfing, Origami, Lapidary, Dance, Basketball

Introduction: My name is Sen. Emmett Berge, I am a funny, vast, charming, courageous, enthusiastic, jolly, famous person who loves writing and wants to share my knowledge and understanding with you.