Skip to content
Related Articles
Open in App
Not now

Related Articles

RSA Algorithm in Cryptography

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 23 Jan, 2023
Improve Article
Save Article

RSA algorithm is an asymmetric cryptography algorithm. Asymmetric actually means that it works on two different keys i.e. Public Key and Private Key. As the name describes that the Public Key is given to everyone and the Private key is kept private.

An example of asymmetric cryptography: 

  1. A client (for example browser) sends its public key to the server and requests some data.
  2. The server encrypts the data using the client’s public key and sends the encrypted data.
  3. The client receives this data and decrypts it.

Since this is asymmetric, nobody else except the browser can decrypt the data even if a third party has the public key of the browser.

The idea! The idea of RSA is based on the fact that it is difficult to factorize a large integer. The public key consists of two numbers where one number is a multiplication of two large prime numbers. And private key is also derived from the same two prime numbers. So if somebody can factorize the large number, the private key is compromised. Therefore encryption strength totally lies on the key size and if we double or triple the key size, the strength of encryption increases exponentially. RSA keys can be typically 1024 or 2048 bits long, but experts believe that 1024-bit keys could be broken in the near future. But till now it seems to be an infeasible task.

Let us learn the mechanism behind the RSA algorithm : >> Generating Public Key: 

Select two prime no's. Suppose P = 53 and Q = 59.
Now First part of the Public key  : n = P*Q = 3127.
 We also need a small exponent say e : 
But e Must be 
An integer.
Not be a factor of n. 
1 < e < Φ(n) [Φ(n) is discussed below], 
Let us now consider it to be equal to 3.
    Our Public Key is made of n and e

>> Generating Private Key: 

We need to calculate Φ(n) :
Such that Φ(n) = (P-1)(Q-1)     
      so,  Φ(n) = 3016
    Now calculate Private Key, d : 
d = (k*Φ(n) + 1) / e for some integer k
For k = 2, value of d is 2011.

Now we are ready with our – Public Key ( n = 3127 and e = 3) and Private Key(d = 2011) Now we will encrypt “HI” :

Convert letters to numbers : H  = 8 and I = 9
    Thus Encrypted Data c = 89e mod n. 
Thus our Encrypted Data comes out to be 1394

Now we will decrypt 1394 : 
    Decrypted Data = cd mod n. 
Thus our Encrypted Data comes out to be 89
8 = H and I = 9 i.e. "HI".

Below is the implementation of the RSA algorithm for 

Method 1: Encrypting and decrypting small numeral values:

C++




// C program for RSA asymmetric cryptographic
// algorithm. For demonstration values are
// relatively small compared to practical
// application
#include <bits/stdc++.h>
using namespace std;
 
// Returns gcd of a and b
int gcd(int a, int h)
{
    int temp;
    while (1) {
        temp = a % h;
        if (temp == 0)
            return h;
        a = h;
        h = temp;
    }
}
 
// Code to demonstrate RSA algorithm
int main()
{
    // Two random prime numbers
    double p = 3;
    double q = 7;
 
    // First part of public key:
    double n = p * q;
 
    // Finding other part of public key.
    // e stands for encrypt
    double e = 2;
    double phi = (p - 1) * (q - 1);
    while (e < phi) {
        // e must be co-prime to phi and
        // smaller than phi.
        if (gcd(e, phi) == 1)
            break;
        else
            e++;
    }
 
    // Private key (d stands for decrypt)
    // choosing d such that it satisfies
    // d*e = 1 + k * totient
    int k = 2; // A constant value
    double d = (1 + (k * phi)) / e;
 
    // Message to be encrypted
    double msg = 12;
 
    printf("Message data = %lf", msg);
 
    // Encryption c = (msg ^ e) % n
    double c = pow(msg, e);
    c = fmod(c, n);
    printf("\nEncrypted data = %lf", c);
 
    // Decryption m = (c ^ d) % n
    double m = pow(c, d);
    m = fmod(m, n);
    printf("\nOriginal Message Sent = %lf", m);
 
    return 0;
}
// This code is contributed by Akash Sharan.

Java




/*package whatever //do not write package name here */
import java.io.*;
import java.math.*;
import java.util.*;
/*
 * Java program for RSA asymmetric cryptographic algorithm.
 * For demonstration, values are
 * relatively small compared to practical application
 */
public class GFG {
  public static double gcd(double a, double h)
  {
    /*
         * This function returns the gcd or greatest common
         * divisor
         */
    double temp;
    while (true) {
      temp = a % h;
      if (temp == 0)
        return h;
      a = h;
      h = temp;
    }
  }
  public static void main(String[] args)
  {
    double p = 3;
    double q = 7;
 
    // Stores the first part of public key:
    double n = p * q;
 
    // Finding the other part of public key.
    // double e stands for encrypt
    double e = 2;
    double phi = (p - 1) * (q - 1);
    while (e < phi) {
      /*
             * e must be co-prime to phi and
             * smaller than phi.
             */
      if (gcd(e, phi) == 1)
        break;
      else
        e++;
    }
    int k = 2; // A constant value
    double d = (1 + (k * phi)) / e;
 
    // Message to be encrypted
    double msg = 12;
 
    System.out.println("Message data = " + msg);
 
    // Encryption c = (msg ^ e) % n
    double c = Math.pow(msg, e);
    c = c % n;
    System.out.println("Encrypted data = " + c);
 
    // Decryption m = (c ^ d) % n
    double m = Math.pow(c, d);
    m = m % n;
    System.out.println("Original Message Sent = " + m);
  }
}
 
// This code is contributed by Pranay Arora.

Python3




# Python for RSA asymmetric cryptographic algorithm.
# For demonstration, values are
# relatively small compared to practical application
import math
 
 
def gcd(a, h):
    temp = 0
    while(1):
        temp = a % h
        if (temp == 0):
            return h
        a = h
        h = temp
 
 
p = 3
q = 7
n = p*q
e = 2
phi = (p-1)*(q-1)
 
while (e < phi):
 
    # e must be co-prime to phi and
    # smaller than phi.
    if(gcd(e, phi) == 1):
        break
    else:
        e = e+1
 
# Private key (d stands for decrypt)
# choosing d such that it satisfies
# d*e = 1 + k * totient
 
k = 2
d = (1 + (k*phi))/e
 
# Message to be encrypted
msg = 12.0
 
print("Message data = ", msg)
 
# Encryption c = (msg ^ e) % n
c = pow(msg, e)
c = math.fmod(c, n)
print("Encrypted data = ", c)
 
# Decryption m = (c ^ d) % n
m = pow(c, d)
m = math.fmod(m, n)
print("Original Message Sent = ", m)
 
 
# This code is contributed by Pranay Arora.

C#




/*
 * C# program for RSA asymmetric cryptographic algorithm.
 * For demonstration, values are
 * relatively small compared to practical application
 */
 
using System;
 
public class GFG {
 
  public static double gcd(double a, double h)
  {
    /*
         * This function returns the gcd or greatest common
         * divisor
         */
    double temp;
    while (true) {
      temp = a % h;
      if (temp == 0)
        return h;
      a = h;
      h = temp;
    }
  }
  static void Main()
  {
    double p = 3;
    double q = 7;
 
    // Stores the first part of public key:
    double n = p * q;
 
    // Finding the other part of public key.
    // double e stands for encrypt
    double e = 2;
    double phi = (p - 1) * (q - 1);
    while (e < phi) {
      /*
             * e must be co-prime to phi and
             * smaller than phi.
             */
      if (gcd(e, phi) == 1)
        break;
      else
        e++;
    }
    int k = 2; // A constant value
    double d = (1 + (k * phi)) / e;
 
    // Message to be encrypted
    double msg = 12;
 
    Console.WriteLine("Message data = "
                      + String.Format("{0:F6}", msg));
 
    // Encryption c = (msg ^ e) % n
    double c = Math.Pow(msg, e);
    c = c % n;
    Console.WriteLine("Encrypted data = "
                      + String.Format("{0:F6}", c));
 
    // Decryption m = (c ^ d) % n
    double m = Math.Pow(c, d);
    m = m % n;
    Console.WriteLine("Original Message Sent = "
                      + String.Format("{0:F6}", m));
  }
}
// This code is contributed by Pranay Arora.

Output

Message data = 12.000000
Encrypted data = 3.000000
Original Message Sent = 12.000000

Method 2: Encrypting and decrypting plain text messages containing alphabets and numbers using their ASCII value:

C++




#include <bits/stdc++.h>
using namespace std;
set<int>
    prime; // a set will be the collection of prime numbers,
           // where we can select random primes p and q
int public_key;
int private_key;
int n;
// we will run the function only once to fill the set of
// prime numbers
void primefiller()
{
    // method used to fill the primes set is seive of
    // eratosthenes(a method to collect prime numbers)
    vector<bool> seive(250, true);
    seive[0] = false;
    seive[1] = false;
    for (int i = 2; i < 250; i++) {
        for (int j = i * 2; j < 250; j += i) {
            seive[j] = false;
        }
    } // filling the prime numbers
    for (int i = 0; i < seive.size(); i++) {
        if (seive[i])
            prime.insert(i);
    }
}
// picking a random prime number and erasing that prime
// number from list because p!=q
int pickrandomprime()
{
    int k = rand() % prime.size();
    auto it = prime.begin();
    while (k--)
        it++;
    int ret = *it;
    prime.erase(it);
    return ret;
}
void setkeys()
{
    int prime1 = pickrandomprime(); // first prime number
    int prime2 = pickrandomprime(); // second prime number
    // to check the prime numbers selected
    // cout<<prime1<<" "<<prime2<<endl;
    n = prime1 * prime2;
    int fi = (prime1 - 1) * (prime2 - 1);
    int e = 2;
    while (1) {
        if (__gcd(e, fi) == 1)
            break;
        e++;
    } // d = (k*Φ(n) + 1) / e for some integer k
    public_key = e;
    int d = 2;
    while (1) {
        if ((d * e) % fi == 1)
            break;
        d++;
    }
    private_key = d;
}
// to encrypt the given number
long long int encrypt(double message)
{
    int e = public_key;
    long long int encrpyted_text = 1;
    while (e--) {
        encrpyted_text *= message;
        encrpyted_text %= n;
    }
    return encrpyted_text;
}
// to decrypt the given number
long long int decrypt(int encrpyted_text)
{
    int d = private_key;
    long long int decrypted = 1;
    while (d--) {
        decrypted *= encrpyted_text;
        decrypted %= n;
    }
    return decrypted;
}
// first converting each character to its ASCII value and
// then encoding it then decoding the number to get the
// ASCII and converting it to character
vector<int> encoder(string message)
{
    vector<int> form;
    // calling the encrypting function in encoding function
    for (auto& letter : message)
        form.push_back(encrypt((int)letter));
    return form;
}
string decoder(vector<int> encoded)
{
    string s;
    // calling the decrypting function decoding function
    for (auto& num : encoded)
        s += decrypt(num);
    return s;
}
int main()
{
    primefiller();
    setkeys();
    string message = "Test Message";
    // uncomment below for manual input
    // cout<<"enter the message\n";getline(cin,message);
    // calling the encoding function
    vector<int> coded = encoder(message);
    cout << "Initial message:\n" << message;
    cout << "\n\nThe encoded message(encrypted by public "
            "key)\n";
    for (auto& p : coded)
        cout << p;
    cout << "\n\nThe decoded message(decrypted by private "
            "key)\n";
    cout << decoder(coded) << endl;
    return 0;
}

Output

Initial message:
Test Message

The encoded message(encrypted by public key)
863312887135951593413927434912887135951359583051879012887

The decoded message(decrypted by private key)
Test Message

This article is contributed by Mohit Gupta_OMG. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!