RSA Algorithm: Theory and Implementation in Python - AskPython (2024)

Cryptography is the practice of securing communication by using codes and ciphers. It includes a variety of techniques for converting plaintext into ciphertext, enabling secure communication, and protecting the confidentiality and integrity of data. Banking, email, e-commerce, and other industries all employ cryptography extensively. In this article you will learn about asymmetric encryption and the RSA algorithm.

Also read: A* Algorithm – Introduction to The Algorithm (With Python Implementation)

Asymmetric Encryption

Asymmetric encryption, commonly referred to as public-key cryptography, uses two distinct keys for encryption and decryption. The public key, which is extensively used to encrypt data and is known to all, is one type of key. The private key, on the other hand, is kept private i.e., only the receiver knows it and is used to decode data.

Both, the public key and the private key should be available at both the sender’s end and the receiver’s end for the asymmetric encryption to succeed.

RSA Algorithm: Theory and Implementation in Python - AskPython (1)

The encryption algorithm receives the sender’s plain text message, encrypts it using the recipient’s public key, and generates a cipher. The recipient then receives this cipher via a transmission or communication channel. The decryption process on the receiver’s end uses the decryption algorithm and the receiver’s private key to recover the original plain text message.

Asymmetric encryption typically consists of three main components:

  1. Key Generation: In this step, a user generates a public-private key pair. The public key is made freely available to anyone who wants to send a message to the user, while the private key is kept secret by the user.
  2. Encryption: In this step, the sender uses the recipient’s public key to encrypt the message. This ensures that only the recipient, who has the corresponding private key, can decrypt and read the message.
  3. Decryption: In this step, the recipient uses their private key to decrypt the message, which was encrypted using their public key. This ensures that only the recipient can read the original message.

Although there are mathematical connections between the public key and the private key, doing so computationally is not practical. This means that anyone can encrypt data using the public key, but only the owner of the private key can decode the data.

Note: A message that is encrypted using a public key can only be decrypted using a private key, while also, a message encrypted using private key can be decrypted using a public key.

Now let us learn about the RSA Algorithm.

RSA Algorithm

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.

The algorithm for RSA is as follows:

  1. Select 2 prime numbers, preferably large, p and q.
  2. Calculate n = p*q.
  3. Calculate phi(n) = (p-1)*(q-1)
  4. Choose a value of e such that 1<e<phi(n) and gcd(phi(n), e) = 1.
  5. Calculate d such that d = (e^-1) mod phi(n).

Here the public key is {e, n} and private key is {d, n}. If M is the plain text then the cipher text C = (M^e) mod n. This is how data is encrypted in RSA algorithm. Similarly, for decryption, the plain text M = (C^d) mod n.

Example: Let p=3 and q=11 (both are prime numbers).

  • Now, n = p*q = 3*11 = 33
  • phi(n) = (p-1)*(q-1) = (3-1)*(11-1) = 2*10 = 20
  • Value of e can be 7 since 1<7<20 and gcd(20, 7) = 1.
  • Calculating d = 7^-1 mod 20 = 3.
  • Therefore, public key = {7, 33} and private key = {3, 33}.

Suppose our message is M=31. You can encrypt and decrypt it using the RSA algorithm as follows:

Encryption: C = (M^e) mod n = 31^7 mod 33 = 4

Decryption: M = (C^d) mod n = 4^3 mod 33 = 31

Since we got the original message that is plain text back after decryption, we can say that the algorithm worked correctly.

Below is the Python code for the implementation of the RSA Algorithm:

import math# step 1p = 3q = 7# step 2n = p*qprint("n =", n)# step 3phi = (p-1)*(q-1)# step 4e = 2while(e<phi): if (math.gcd(e, phi) == 1): break else: e += 1print("e =", e)# step 5k = 2d = ((k*phi)+1)/eprint("d =", d)print(f'Public key: {e, n}')print(f'Private key: {d, n}')# plain textmsg = 11print(f'Original message:{msg}')# encryptionC = pow(msg, e)C = math.fmod(C, n)print(f'Encrypted message: {C}')# decryptionM = pow(C, d)M = math.fmod(M, n)print(f'Decrypted message: {M}') 

Output:

n = 21e = 5d = 5.0Public key: (5, 21)Private key: (5.0, 21)Original message:11Encrypted message: 2.0Decrypted message: 11.0

Being able to do both encryption and digital signatures is one of the RSA algorithm’s key benefits. To confirm that the message has not been tampered with, digital signatures are made by encrypting a message hash with the sender’s private key. This encryption may then be validated by anybody with access to the sender’s public key.

Conclusion

You gained knowledge of symmetric encryption and the RSA algorithm in this article. You also saw how the RSA algorithm was implemented in Python.

Please visitaskpython.comfor more such easy-to-understand Python tutorials.

Reference

RSA Algorithm: Theory and Implementation in Python - AskPython (2024)

FAQs

How to implement RSA algorithm in Python? ›

To implement RSA in Python: Generate large prime numbers p and q. Compute n = p*q and Euler's totient function φ(n). Choose e such that 1 < e < φ(n) and gcd(e, φ(n)) = 1. Compute d such that (d * e) % φ(n) = 1.

How is the RSA algorithm implemented? ›

Secure key exchange

The two parties involved generate a public-private key pair using the RSA algorithm. The sender generates a symmetric key, encrypts it using the receiver's public key, and sends the encrypted key to the receiver. The receiver then decrypts it using the private key.

What is the theory of RSA algorithm? ›

The RSA algorithm uses two keys, d and e, which work in pairs, for decryption and encryption, respectively. Thus, one can apply the encrypting transformation first and then the decrypting one, or the decrypting transformation first followed by the encrypting one.

What is the equation for RSA in Python? ›

RSA Key Generation:

Choose two large prime numbers p and q. Calculate n=p*q. Select public key e such that it is not a factor of (p-1)*(q-1) Select private key d such that the following equation is true (d*e)mod(p-1)(q-1)=1 or d is inverse of E in modulo (p-1)*(q-1)

What is the formula for RSA algorithm? ›

➢ To create an RSA public/private key pair, here are the basic steps: 1- Choose two prime numbers, p and q such that p ≠ q . 2- Calculate the modulus, n = p × q. 3- Calcuate ϕ( n ) = ( p – 1 ) × ( q – 1 ). 4- Select integer e such that gcd (ϕ( n ), e) = 1 and 1 < e < ϕ( n ).

What is the RSA algorithm in a nutshell? ›

The Background — In a Nutshell. RSA is an asymmetric cryptographic system that consists of a Public Key and a Private Key. Encryption is done via the public key while decryption is achieved through the private key.

What is the workflow of RSA algorithm? ›

The application of the RSA algorithm consists of three main processes, namely key generation, encryption, and decryption [26] . ... E-business security becomes an important issue in the development of technology, to ensure the safety and comfort of transactions in the exchange of information is privacy.

What are two applications of RSA algorithm? ›

RSA is an important milestone in the field of message communication networks and is widely utilized in various applications such as online banking, e-commerce, and email . The RSA algorithm is the first public key cryptosystem and is based on the hardness of the Integer Factorization problem .

Top Articles
Crypto firms introduce risk assessments and finance tests in response to strict new rules in UK
8 Sustainable Side Hustles That Will Make You Money | Entrepreneur
Omega Pizza-Roast Beef -Seafood Middleton Menu
Jonathon Kinchen Net Worth
Jefferey Dahmer Autopsy Photos
Co Parts Mn
Is Csl Plasma Open On 4Th Of July
Optum Medicare Support
Https //Advanceautoparts.4Myrebate.com
Signs Of a Troubled TIPM
OpenXR support for IL-2 and DCS for Windows Mixed Reality VR headsets
U/Apprenhensive_You8924
Bcbs Prefix List Phone Numbers
Patrick Bateman Notebook
boohoo group plc Stock (BOO) - Quote London S.E.- MarketScreener
Gdlauncher Downloading Game Files Loop
Destiny 2 Salvage Activity (How to Complete, Rewards & Mission)
Paychex Pricing And Fees (2024 Guide)
Willam Belli's Husband
Marvon McCray Update: Did He Pass Away Or Is He Still Alive?
Palm Springs Ca Craigslist
Lowes Undermount Kitchen Sinks
Bernie Platt, former Cherry Hill mayor and funeral home magnate, has died at 90
Heart and Vascular Clinic in Monticello - North Memorial Health
How to Grow and Care for Four O'Clock Plants
Ou Class Nav
Workshops - Canadian Dam Association (CDA-ACB)
Booknet.com Contract Marriage 2
Dtm Urban Dictionary
Firefly Festival Logan Iowa
Khatrimmaza
Goodwill Thrift Store & Donation Center Marietta Photos
John F Slater Funeral Home Brentwood
Marcus Roberts 1040 Answers
NHL training camps open with Swayman's status with the Bruins among the many questions
Fototour verlassener Fliegerhorst Schönwald [Lost Place Brandenburg]
Daily Times-Advocate from Escondido, California
Tyler Perry Marriage Counselor Play 123Movies
Skyward Marshfield
Tripadvisor Vancouver Restaurants
Stranahan Theater Dress Code
Alpha Labs Male Enhancement – Complete Reviews And Guide
Pathfinder Wrath Of The Righteous Tiefling Traitor
Eat Like A King Who's On A Budget Copypasta
Squalicum Family Medicine
Amateur Lesbian Spanking
Tito Jackson, member of beloved pop group the Jackson 5, dies at 70
Minecraft: Piglin Trade List (What Can You Get & How)
Food and Water Safety During Power Outages and Floods
Ewwwww Gif
Lorcin 380 10 Round Clip
Latest Posts
Article information

Author: Pres. Lawanda Wiegand

Last Updated:

Views: 5783

Rating: 4 / 5 (51 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Pres. Lawanda Wiegand

Birthday: 1993-01-10

Address: Suite 391 6963 Ullrich Shore, Bellefort, WI 01350-7893

Phone: +6806610432415

Job: Dynamic Manufacturing Assistant

Hobby: amateur radio, Taekwondo, Wood carving, Parkour, Skateboarding, Running, Rafting

Introduction: My name is Pres. Lawanda Wiegand, I am a inquisitive, helpful, glamorous, cheerful, open, clever, innocent person who loves writing and wants to share my knowledge and understanding with you.