The Wayback Machine - https://web.archive.org/web/20240915025143/https://www.geeksforgeeks.org/rsa-algorithm-cryptography/
Open In App

RSA Algorithm in Cryptography

Last Updated : 11 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

RSA algorithm is an asymmetric cryptography algorithm. Asymmetric means that it works on two different keys i.e. Public Key and Private Key. As the name describes 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 lies in 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 shortly. 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.
Python
# 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.
Javascript
//GFG
//Javascript code for this approach
function gcd(a, h) {
  /*
   * This function returns the gcd or greatest common
   * divisor
   */
  let temp;
  while (true) {
    temp = a % h;
    if (temp == 0) return h;
    a = h;
    h = temp;
  }
}

let p = 3;
let q = 7;

// Stores the first part of public key:
let n = p * q;

// Finding the other part of public key.
// e stands for encrypt
let e = 2;
let 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++;
}
let k = 2; // A constant value
let d = (1 + (k * phi)) / e;

// Message to be encrypted
let msg = 12;

console.log("Message data = " + msg);

// Encryption c = (msg ^ e) % n
let c = Math.pow(msg, e);
c = c % n;
console.log("Encrypted data = " + c);

// Decryption m = (c ^ d) % n
let m = Math.pow(c, d);
m = m % n;
console.log("Original Message Sent = " + m);

//This code is written by Sundaram

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;
}
Java
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;

public class GFG {
    private static HashSet<Integer> prime = new HashSet<>();
    private static Integer public_key = null;
    private static Integer private_key = null;
    private static Integer n = null;
    private static Random random = new Random();

    public static void main(String[] args)
    {
        primeFiller();
        setKeys();
        String message = "Test Message";
        // Uncomment below for manual input
        // System.out.println("Enter the message:");
        // message = new Scanner(System.in).nextLine();

        List<Integer> coded = encoder(message);

        System.out.println("Initial message:");
        System.out.println(message);
        System.out.println(
            "\n\nThe encoded message (encrypted by public key)\n");
        System.out.println(
            String.join("", coded.stream()
                                .map(Object::toString)
                                .toArray(String[] ::new)));
        System.out.println(
            "\n\nThe decoded message (decrypted by public key)\n");
        System.out.println(decoder(coded));
    }

    public static void primeFiller()
    {
        boolean[] sieve = new boolean[250];
        for (int i = 0; i < 250; i++) {
            sieve[i] = true;
        }

        sieve[0] = false;
        sieve[1] = false;

        for (int i = 2; i < 250; i++) {
            for (int j = i * 2; j < 250; j += i) {
                sieve[j] = false;
            }
        }

        for (int i = 0; i < sieve.length; i++) {
            if (sieve[i]) {
                prime.add(i);
            }
        }
    }

    public static int pickRandomPrime()
    {
        int k = random.nextInt(prime.size());
        List<Integer> primeList = new ArrayList<>(prime);
        int ret = primeList.get(k);
        prime.remove(ret);
        return ret;
    }

    public static void setKeys()
    {
        int prime1 = pickRandomPrime();
        int prime2 = pickRandomPrime();

        n = prime1 * prime2;
        int fi = (prime1 - 1) * (prime2 - 1);

        int e = 2;
        while (true) {
            if (gcd(e, fi) == 1) {
                break;
            }
            e += 1;
        }

        public_key = e;

        int d = 2;
        while (true) {
            if ((d * e) % fi == 1) {
                break;
            }
            d += 1;
        }

        private_key = d;
    }

    public static int encrypt(int message)
    {
        int e = public_key;
        int encrypted_text = 1;
        while (e > 0) {
            encrypted_text *= message;
            encrypted_text %= n;
            e -= 1;
        }
        return encrypted_text;
    }

    public static int decrypt(int encrypted_text)
    {
        int d = private_key;
        int decrypted = 1;
        while (d > 0) {
            decrypted *= encrypted_text;
            decrypted %= n;
            d -= 1;
        }
        return decrypted;
    }

    public static int gcd(int a, int b)
    {
        if (b == 0) {
            return a;
        }
        return gcd(b, a % b);
    }

    public static List<Integer> encoder(String message)
    {
        List<Integer> encoded = new ArrayList<>();
        for (char letter : message.toCharArray()) {
            encoded.add(encrypt((int)letter));
        }
        return encoded;
    }

    public static String decoder(List<Integer> encoded)
    {
        StringBuilder s = new StringBuilder();
        for (int num : encoded) {
            s.append((char)decrypt(num));
        }
        return s.toString();
    }
}
Python
import random
import math

# A set will be the collection of prime numbers,
# where we can select random primes p and q
prime = set()

public_key = None
private_key = None
n = None

# We will run the function only once to fill the set of
# prime numbers
def primefiller():
    # Method used to fill the primes set is Sieve of
    # Eratosthenes (a method to collect prime numbers)
    seive = [True] * 250
    seive[0] = False
    seive[1] = False
    for i in range(2, 250):
        for j in range(i * 2, 250, i):
            seive[j] = False

    # Filling the prime numbers
    for i in range(len(seive)):
        if seive[i]:
            prime.add(i)


# Picking a random prime number and erasing that prime
# number from list because p!=q
def pickrandomprime():
    global prime
    k = random.randint(0, len(prime) - 1)
    it = iter(prime)
    for _ in range(k):
        next(it)

    ret = next(it)
    prime.remove(ret)
    return ret


def setkeys():
    global public_key, private_key, n
    prime1 = pickrandomprime()  # First prime number
    prime2 = pickrandomprime()  # Second prime number

    n = prime1 * prime2
    fi = (prime1 - 1) * (prime2 - 1)

    e = 2
    while True:
        if math.gcd(e, fi) == 1:
            break
        e += 1

    # d = (k*Φ(n) + 1) / e for some integer k
    public_key = e

    d = 2
    while True:
        if (d * e) % fi == 1:
            break
        d += 1

    private_key = d


# To encrypt the given number
def encrypt(message):
    global public_key, n
    e = public_key
    encrypted_text = 1
    while e > 0:
        encrypted_text *= message
        encrypted_text %= n
        e -= 1
    return encrypted_text


# To decrypt the given number
def decrypt(encrypted_text):
    global private_key, n
    d = private_key
    decrypted = 1
    while d > 0:
        decrypted *= encrypted_text
        decrypted %= n
        d -= 1
    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
def encoder(message):
    encoded = []
    # Calling the encrypting function in encoding function
    for letter in message:
        encoded.append(encrypt(ord(letter)))
    return encoded


def decoder(encoded):
    s = ''
    # Calling the decrypting function decoding function
    for num in encoded:
        s += chr(decrypt(num))
    return s


if __name__ == '__main__':
    primefiller()
    setkeys()
    message = "Test Message"
    # Uncomment below for manual input
    # message = input("Enter the message\n")
    # Calling the encoding function
    coded = encoder(message)

    print("Initial message:")
    print(message)
    print("\n\nThe encoded message(encrypted by public key)\n")
    print(''.join(str(p) for p in coded))
    print("\n\nThe decoded message(decrypted by public key)\n")
    print(''.join(str(p) for p in decoder(coded)))
    
    
C#
using System;
using System.Collections.Generic;

public class GFG
{
    private static HashSet<int> prime = new HashSet<int>();
    private static int? public_key = null;
    private static int? private_key = null;
    private static int? n = null;
    private static Random random = new Random();

    public static void Main()
    {
        PrimeFiller();
        SetKeys();
        string message = "Test Message";
        // Uncomment below for manual input
        // Console.WriteLine("Enter the message:");
        // message = Console.ReadLine();

        List<int> coded = Encoder(message);

        Console.WriteLine("Initial message:");
        Console.WriteLine(message);
        Console.WriteLine("\n\nThe encoded message (encrypted by public key)\n");
        Console.WriteLine(string.Join("", coded));
        Console.WriteLine("\n\nThe decoded message (decrypted by public key)\n");
        Console.WriteLine(Decoder(coded));
    }

    public static void PrimeFiller()
    {
        bool[] sieve = new bool[250];
        for (int i = 0; i < 250; i++)
        {
            sieve[i] = true;
        }

        sieve[0] = false;
        sieve[1] = false;

        for (int i = 2; i < 250; i++)
        {
            for (int j = i * 2; j < 250; j += i)
            {
                sieve[j] = false;
            }
        }

        for (int i = 0; i < sieve.Length; i++)
        {
            if (sieve[i])
            {
                prime.Add(i);
            }
        }
    }

    public static int PickRandomPrime()
    {
        int k = random.Next(0, prime.Count - 1);
        var enumerator = prime.GetEnumerator();
        for (int i = 0; i <= k; i++)
        {
            enumerator.MoveNext();
        }

        int ret = enumerator.Current;
        prime.Remove(ret);
        return ret;
    }

    public static void SetKeys()
    {
        int prime1 = PickRandomPrime();
        int prime2 = PickRandomPrime();

        n = prime1 * prime2;
        int fi = (prime1 - 1) * (prime2 - 1);

        int e = 2;
        while (true)
        {
            if (GCD(e, fi) == 1)
            {
                break;
            }
            e += 1;
        }

        public_key = e;

        int d = 2;
        while (true)
        {
            if ((d * e) % fi == 1)
            {
                break;
            }
            d += 1;
        }

        private_key = d;
    }
     public static int Encrypt(int message)
    {
        int e = public_key.Value;
        int encrypted_text = 1;
        while (e > 0)
        {
            encrypted_text *= message;
            encrypted_text %= n.Value;
            e -= 1;
        }
        return encrypted_text;
    }

    public static int Decrypt(int encrypted_text)
    {
        int d = private_key.Value;
        int decrypted = 1;
        while (d > 0)
        {
            decrypted *= encrypted_text;
            decrypted %= n.Value;
            d -= 1;
        }
        return decrypted;
    }
    public static int GCD(int a, int b)
    {
        if (b == 0)
        {
            return a;
        }
        return GCD(b, a % b);
    }

    public static List<int> Encoder(string message)
    {
        List<int> encoded = new List<int>();
        foreach (char letter in message)
        {
            encoded.Add(Encrypt((int)letter));
        }
        return encoded;
    }

    public static string Decoder(List<int> encoded)
    {
        string s = "";
        foreach (int num in encoded)
        {
            s += (char)Decrypt(num);
        }
        return s;
    }

   
}

Output
Initial message:
Test Message

The encoded message(encrypted by public key)
863312887135951593413927434912887135951359583051879012887

The decoded message(decrypted by private key)
Test Message

 

Implementation of RSA Cryptosystem using Primitive Roots in C++

we will implement a simple version of RSA using primitive roots.

Step 1: Generating Keys

  • To start, we need to generate two large prime numbers, p and q. These primes should be of roughly equal length and their product should be much larger than the message we want to encrypt.
  • We can generate the primes using any primality testing algorithm, such as the Miller-Rabin test. Once we have the two primes, we can compute their product n = p*q, which will be the modulus for our RSA system.
  • Next, we need to choose an integer e such that 1 < e < phi(n) and gcd(e, phi(n)) = 1, where phi(n) = (p-1)*(q-1) is Euler’s totient function. This value of e will be the public key exponent.
  • To compute the private key exponent d, we need to find an integer d such that d*e = 1 (mod phi(n)). This can be done using the extended Euclidean algorithm.
  • Our public key is (n, e) and our private key is (n, d).

Step 2: Encryption

  • To encrypt a message m, we need to convert it to an integer between 0 and n-1. This can be done using a reversible encoding scheme, such as ASCII or UTF-8.
  • Once we have the integer representation of the message, we compute the ciphertext c as c = m^e (mod n). This can be done efficiently using modular exponentiation algorithms, such as binary exponentiation.

Step 3: Decryption

  • To decrypt the ciphertext c, we compute the plaintext m as m = c^d (mod n). Again, we can use modular exponentiation algorithms to do this efficiently.

Step 4: Example

  • Let’s walk through an example using small values to illustrate how the RSA cryptosystem works.
  • Suppose we choose p = 11 and q = 13, giving us n = 143 and phi(n) = 120. We can choose e = 7, since gcd(7, 120) = 1. Using the extended Euclidean algorithm, we can compute d = 103, since 7*103 = 1 (mod 120).
  • Our public key is (143, 7) and our private key is (143, 103).
  • Suppose we want to encrypt the message “HELLO”. We can convert this to the integer 726564766, using ASCII encoding. Using the public key, we compute the ciphertext as c = 726564766^7 (mod 143) = 32.
  • To decrypt the ciphertext, we use the private key to compute m = 32^103 (mod 143) = 726564766, which is the original message.

Example Code:

C++
#include <iostream>
#include <cmath>
using namespace std;

// calculate phi(n) for a given number n
int phi(int n) {
   int result = n;
   for (int i = 2; i <= sqrt(n); i++) {
       if (n % i == 0) {
           while (n % i == 0) {
               n /= i;
           }
           result -= result / i;
       }
   }
   if (n > 1) {
       result -= result / n;
   }
   return result;
}

// calculate gcd(a, b) using the Euclidean algorithm
int gcd(int a, int b) {
   if (b == 0) {
       return a;
   }
   return gcd(b, a % b);
}

// calculate a^b mod m using modular exponentiation
int modpow(int a, int b, int m) {
   int result = 1;
   while (b > 0) {
       if (b & 1) {
           result = (result * a) % m;
       }
       a = (a * a) % m;
       b >>= 1;
   }
   return result;
}

// generate a random primitive root modulo n
int generatePrimitiveRoot(int n) {
   int phiN = phi(n);
   int factors[phiN], numFactors = 0;
   int temp = phiN;
   // get all prime factors of phi(n)
   for (int i = 2; i <= sqrt(temp); i++) {
       if (temp % i == 0) {
           factors[numFactors++] = i;
           while (temp % i == 0) {
               temp /= i;
           }
       }
   }
   if (temp > 1) {
       factors[numFactors++] = temp;
   }
   // test possible primitive roots
   for (int i = 2; i <= n; i++) {
       bool isRoot = true;
       for (int j = 0; j < numFactors; j++) {
           if (modpow(i, phiN / factors[j], n) == 1) {
               isRoot = false;
               break;
           }
       }
       if (isRoot) {
           return i;
       }
   }
   return -1;
}

int main() {
   int p = 11;
   int q = 13;
   int n = p * q;
   int phiN = (p - 1) * (q - 1);
   // phi(n) = 120
   int e = 7; // gcd(7, 120) = 1 
   int d = 0;
   while ((d * e) % phiN != 1) {
       d++;
   }
   
   cout << "Public key: {" << e << ", " << n << "}" << endl;
   cout << "Private key: {" << d << ", " << n << "}" << endl;
   int m = 11;
   int c = modpow(m, e, n);
   int decrypted = modpow(c, d, n);
   cout << "Original message: " << m << endl;
   cout << "Encrypted message: " << c << endl;
   cout << "Decrypted message: " << decrypted << endl;
   return 0;
}

// This code is modified by Susobhan Akhuli
Java
import java.util.*;

public class GFG {

    // calculate phi(n) for a given number n
    static int phi(int n) {
        int result = n;
        for (int i = 2; i <= Math.sqrt(n); i++) {
            if (n % i == 0) {
                while (n % i == 0) {
                    n /= i;
                }
                result -= result / i;
            }
        }
        if (n > 1) {
            result -= result / n;
        }
        return result;
    }

    // calculate gcd(a, b) using the Euclidean algorithm
    static int gcd(int a, int b) {
        if (b == 0) {
            return a;
        }
        return gcd(b, a % b);
    }

    // calculate a^b mod m using modular exponentiation
    static int modpow(int a, int b, int m) {
        int result = 1;
        while (b > 0) {
            if ((b & 1) == 1) {
                result = (result * a) % m;
            }
            a = (a * a) % m;
            b >>= 1;
        }
        return result;
    }

    // generate a random primitive root modulo n
    static int generatePrimitiveRoot(int n) {
        int phiN = phi(n);
        List<Integer> factors = new ArrayList<>();
        int temp = phiN;
        // get all prime factors of phi(n)
        for (int i = 2; i <= Math.sqrt(temp); i++) {
            if (temp % i == 0) {
                factors.add(i);
                while (temp % i == 0) {
                    temp /= i;
                }
            }
        }
        if (temp > 1) {
            factors.add(temp);
        }
        // test possible primitive roots
        for (int i = 2; i <= n; i++) {
            boolean isRoot = true;
            for (int factor : factors) {
                if (modpow(i, phiN / factor, n) == 1) {
                    isRoot = false;
                    break;
                }
            }
            if (isRoot) {
                return i;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int p = 11;
        int q = 13;
        int n = p * q;
        int phiN = (p - 1) * (q - 1);
        // phi(n) = 120
        int e = 7; // gcd(7, 120) = 1 
        int d = 0;
        while ((d * e) % phiN != 1) {
            d++;
        }

        System.out.println("Public key: {" + e + ", " + n + "}");
        System.out.println("Private key: {" + d + ", " + n + "}");
        int m = 11;
        int c = modpow(m, e, n);
        int decrypted = modpow(c, d, n);
        System.out.println("Original message: " + m);
        System.out.println("Encrypted message: " + c);
        System.out.println("Decrypted message: " + decrypted);
    }
}

// This code is contributed by Susobhan Akhuli

Output
Public key: {7, 143}
Private key: {103, 143}
Original message: 11
Encrypted message: 132
Decrypted message: 11

Advantages

  • Security: RSA algorithm is considered to be very secure and is widely used for secure data transmission.
  • Public-key cryptography: RSA algorithm is a public-key cryptography algorithm, which means that it uses two different keys for encryption and decryption. The public key is used to encrypt the data, while the private key is used to decrypt the data.
  • Key exchange: RSA algorithm can be used for secure key exchange, which means that two parties can exchange a secret key without actually sending the key over the network.
  • Digital signatures: RSA algorithm can be used for digital signatures, which means that a sender can sign a message using their private key, and the receiver can verify the signature using the sender’s public key.
  • Speed: The RSA technique is suited for usage in real-time applications since it is quite quick and effective.
  • Widely used: Online banking, e-commerce, and secure communications are just a few fields and applications where the RSA algorithm is extensively developed.

Disadvantages

  • Slow processing speed: RSA algorithm is slower than other encryption algorithms, especially when dealing with large amounts of data.
  • Large key size: RSA algorithm requires large key sizes to be secure, which means that it requires more computational resources and storage space.
  • Vulnerability to side-channel attacks: RSA algorithm is vulnerable to side-channel attacks, which means an attacker can use information leaked through side channels such as power consumption, electromagnetic radiation, and timing analysis to extract the private key.
  • Limited use in some applications: RSA algorithm is not suitable for some applications, such as those that require constant encryption and decryption of large amounts of data, due to its slow processing speed.
  • Complexity: The RSA algorithm is a sophisticated mathematical technique that some individuals may find challenging to comprehend and use.
  • Key Management: The secure administration of the private key is necessary for the RSA algorithm, although in some cases this can be difficult.
  • Vulnerability to Quantum Computing: Quantum computers have the ability to attack the RSA algorithm, potentially decrypting the data.

Conclusion

In conclusion, while RSA offers significant advantages like security, public-key cryptography, key exchange, digital signatures, speed, and widespread use, it’s essential to acknowledge its limitations. The algorithm’s computational intensity, particularly with larger key sizes, can impact performance, and vulnerabilities like side-channel attacks remain a concern.

Frequently Asked Questions on RSA Algorithm in Cryptography – FAQs

What is the RSA algorithm, and how does it work?

RSA is an asymmetric encryption algorithm that uses public and private keys to secure data. It relies on the mathematical challenge of factoring large numbers, making it computationally difficult for unauthorized parties to decrypt messages.

What are the key components of the RSA algorithm?

The key components include:

  • Public Key: Used for encryption and shared openly.
  • Private Key: Used for decryption and kept secret.
  • Modulus (n): The product of two large prime numbers.
  • Public Exponent (e): A number coprime to phi(n).
  • Private Exponent (d): The modular multiplicative inverse of e.

What are the primary applications of RSA?

RSA finds applications in:

  • Secure Data Transmission: Encrypting data for confidentiality.
  • Key Exchange: Establishing shared secret keys.
  • Digital Signatures: Verifying the authenticity and integrity of messages.

Is RSA vulnerable to quantum computing?

Yes, RSA is vulnerable to quantum computing attacks, as quantum computers could efficiently factor large numbers, undermining the algorithm’s security. However, ongoing research aims to develop quantum-resistant cryptographic algorithms.

How can I ensure the security of RSA encryption?

To enhance RSA security:

  • Use Strong Keys: Employ sufficiently large key sizes (e.g., 2048 bits or higher).
  • Protect Private Keys: Store private keys securely and avoid sharing them.
  • Implement Side-Channel Attack Mitigations: Use techniques to reduce information leakage.
  • Stay Informed: Keep updated on advancements in cryptography and vulnerabilities.


Previous Article
Next Article

Similar Reads

Classical Cryptography and Quantum Cryptography
Cryptography is the technique that is used for secure communication between two parties in a public environment where unauthorized users and malicious attackers are present. In cryptography, there are two processes i.e. encryption and decryption performed at the sender and receiver end respectively. Encryption is the process where simple multimedia
7 min read
RSA Algorithm using Multiple Precision Arithmetic Library
Public Key Cryptography is also known as Asymmetric Cryptography is the type of cryptography which involves the usage of two keys namely Public Key and Private Key. The Public Key of the receiver is used to encrypt the plaintext by the sender while the Private Key of the receiver is used to decrypt the encrypted message and hence can be decrypted o
4 min read
How to solve RSA Algorithm Problems?
RSA algorithm is an asymmetric cryptography algorithm which means, there should be two keys involve while communicating, i.e., public key and private key. There are simple steps to solve problems on the RSA Algorithm. Example-1: Step-1: Choose two prime number [Tex]p [/Tex]and [Tex]q [/Tex]Lets take [Tex]p = 3 [/Tex]and [Tex]q = 11 [/Tex]Step-2: Co
8 min read
Difference between RSA algorithm and DSA
In cryptography, the two commonly used algorithms in modern cryptography for secure data transmission and to ensure the signatures of digital signatures, are the Rivest-Shamir-Adleman (RSA) algorithm and Digital Signature Algorithm (DSA). We'll learn about RSA and DSA, how they work when are they used, and their differences. What is RSA?RSA stands
8 min read
Shamir's Secret Sharing Algorithm | Cryptography
Cryptography is a technique of securing information and communications through the use of codes so that only those person for whom the information is intended can understand it and process it. Thus preventing unauthorized access to information. The prefix “crypt” means “hidden” and suffix graphy means “writing”. In this article, a type of cryptogra
7 min read
CAST Algorithm in Cryptography
CAST is a general procedure for creating a family of block ciphers. Individual ciphers have names like CAST-128 and CAST-256. The article focuses on discussing the CAST algorithm in cryptography. What is CAST Algorithm?The CAST algorithm is generally used in IP security and follows the Fiestal structure, as the Fiestal structure divides the plain t
4 min read
How Hashing Algorithm Used in Cryptography?
A Hash Function (H) takes a variable-length block of data and returns a hash value of a fixed size. A good hash function has a property that when it is applied to a large number of inputs, the outputs will be evenly distributed and appear random. Generally, the primary purpose of a hash function is to maintain data integrity. Any change to any bits
12 min read
How Does a Secure Hash Algorithm work in Cryptography?
Cryptography is very much essential and vital for data encryption and decryption to safeguard sensitive and touchy data in businesses and individual. However, with the advancement of technology data breaches and cyberattacks has become very common, and need to employ different types of cryptography tools to combat such issues and problems. Hashing
9 min read
Knapsack Encryption Algorithm in Cryptography
Knapsack Encryption Algorithm is the first general public key cryptography algorithm. It was developed by Ralph Merkle and Mertin Hellman in 1978. As it is a Public key cryptography, it needs two different keys. One is the Public key which is used for the Encryption process and the other one is the Private key which is used for the Decryption proce
6 min read
Weak RSA decryption with Chinese-remainder theorem
Prerequisite : RSA Algorithm Why RSA decryption is slow ? RSA decryption is slower than encryption because while doing decryption, private key parameter " d " is necessarily large. Moreover the parameters - " p and q " are two very large Prime Numbers. Given integers c, e, p and q, find m such that c = pow(m, e) mod (p * q) (RSA decryption for weak
4 min read
RSA Blind Signatures
Blind signatures are a form of digital signature in which the content of the message is hidden (blinded) before it is signed by any of the authorities involved in the process. This technique provides invisibility to the person who made the message. It is mainly used when the author and the signer are different parties. Blind signatures can be imple
8 min read
Chosen Ciphertext Attacks on RSA
In the domain of cryptography, a chosen ciphertext attack (CCA) is a significant threat, particularly to public-key cryptosystems. This article aims to resolve the complexities of chosen-ciphertext attacks, exploring their implications and impact on various cryptographic schemes. Terminology on Cipher Text AttacksChosen-Ciphertext Attack (CCA): A c
3 min read
RSA and Digital Signatures
RSA and digital signatures are crucial elements in modern cybersecurity. RSA, a widely used encryption algorithm, ensures secure data transmission by encrypting and decrypting information. Digital signatures, on the other hand, authenticate the identity of the sender and guarantee the integrity of the message. Together, RSA and digital signatures p
8 min read
Security of RSA
Rivest-Shamir-Adleman (RSA) encryption is a foundational element of modern cryptography, crucial for securing data transmission over the internet. Developed by Rivest, Shamir, and Adleman, RSA relies on the mathematical difficulty of factoring large prime numbers, making it a robust public-key cryptosystem. It's widely used in applications like HTT
4 min read
Difference Between AES and RSA Encryption
In cryptography, this is the process of changing or transforming plain text or information into a cipher text or a text that the receiver, who is the person to whom the information is intended, can only decode. There are several algorithms in data encryption such as AES and RSA. AES represents a symmetric key algorithm whose processes depend on the
6 min read
Difference Between Diffie-Hellman and RSA
Cyber Security is the branch of computers dealing with networks and technology to protect the computer system from unauthorized third-party users which aim at accessing and stealing user information and contribute to causing damage to the system. Cyber security intentions at implementing best practices to save computers/ laptops/ mobiles from any k
6 min read
History of Cryptography
Humans have two basic needs when we take about communication. One is the need to communicate selectively, to communicate and share information. These two basic needs while communicating gave rise to coding and encrypting the messages in such a way that only intended people could have access to the information. The word 'cryptography' originated fro
4 min read
Differences between Classical and Quantum Cryptography
Classical Cryptography: Classical cryptography is based on mathematics and it relies on the computational difficulty of factorizing large number. The security of classical cryptography is based on the high complexity of the mathematical problem for the instance factorization of large number. Quantum Cryptography: Quantum Cryptography is based on ph
1 min read
Bifid Cipher in Cryptography
This cipher technique considered more secure compared to other substitution algorithms reason being it breaks the message apart into two separate streams and then recombines them. It is a combination of the Polybius square with the transposition and uses fractionation to achieve diffusion. This encrypting technique invented by Felin Delastelle. It
4 min read
Cryptography and Network Security Principles
In present day scenario security of the system is the sole priority of any organisation. The main aim of any organisation is to protect their data from attackers. In cryptography, attacks are of two types such as Passive attacks and Active attacks. Passive attacks are those that retrieve information from the system without affecting the system reso
3 min read
Fernet (symmetric encryption) using Cryptography module in Python
Cryptography is the practice of securing useful information while transmitting from one computer to another or storing data on a computer. Cryptography deals with the encryption of plaintext into ciphertext and decryption of ciphertext into plaintext. Python supports a cryptography package that helps us encrypt and decrypt data. The fernet module o
3 min read
Password Entropy in Cryptography
Password Entropy is the measure of password strength or how strong the given password is. It is a measure of effectiveness of a password against guessing or brute-force attacks. It decides whether the entered password is common and easily crack-able or not. It is calculated by knowing character set (lower alphabets, upper alphabets, numbers, symbol
3 min read
Difference between Cryptography and Cyber Security
In today's world, where technology has become an integral part of our lives, ensuring the security of our digital data has become more important than ever. Cryptography and Cyber Security are two terms that are often used interchangeably, but they have different meanings and purposes. In this article, we will explore the differences between these t
4 min read
Merkle-Damgard Scheme in Cryptography
Pre-requisites: Cryptography and its Types MD scheme(discovered by Ralph Merkle) is used to build collision-resistant cryptographic hash functions from collision-resistant one-way compression functions. It is used in algorithms like SHA-1, SHA-256, etc. This scheme can be divided into two stages: Stage 1: Design a fixed-length, collision-resistant
4 min read
PRG, PRF and PRP in Cryptography
Cryptography is the study and practice of techniques for secure communication in the presence of third parties called adversaries. It deals with developing and analyzing protocols that prevent malicious third parties from retrieving information being shared between two entities thereby following the various aspects of information security. In this
2 min read
What is p-box in Cryptography?
P-boxes are permutation boxes which are usually one of the main components of a modern block cipher. They are also known as D-boxes or diffusion boxes. P-boxes are used in the block cipher called the data encryption standard commonly known as DES in cryptography. In this article, we will look into what are p-boxes, the types of p-boxes, and how to
5 min read
Post Quantum Cryptography in Computer Network
Post-quantum cryptography (PQC), also known as quantum-resistant cryptography, is a branch of cryptography. It is also protected against quantum computer attacks. Quantum computers are a new type of computer that uses the principles of quantum mechanics to carry out calculations. Quantum mechanics is a branch of physics that researches the nature o
5 min read
Cryptography in Wireless Sensor Networks
Wireless Sensor Networks (WSNs) have turned out to be indispensable in diverse programs, along with environmental tracking, healthcare, industrial automation, and clever cities. However, those networks are regularly deployed in hard and potentially opposed environments, making statistics safety a pinnacle precedence. Cryptography, the science of se
6 min read
Cryptography in Industrial Control Systems (ICS)
Cryptography plays a crucial role in securing data and communication in the Industrial Control Systems (ICS) which encompass the technology and processes used to control and automate industrial operations. This article explores the fundamental aspects of the cryptography in context of the ICS ensuring the confidentiality, integrity, and authenticit
2 min read
Vernam Cipher in Cryptography
Vernam Cipher is a method of encrypting alphabetic text. It is one of the Substitution techniques for converting plain text into cipher text. In this mechanism, we assign a number to each character of the Plain-Text, like (a = 0, b = 1, c = 2, ... z = 25). Method to take key: In the Vernam cipher algorithm, we take a key to encrypt the plain text w
6 min read