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

RSA Algorithm in Cryptography

Last Updated : 06 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

RSA(Rivest-Shamir-Adleman) Algorithm is an asymmetric or public-key cryptography algorithm which means it works on two different keys: Public Key and Private Key. The Public Key is used for encryption and is known to everyone, while the Private Key is used for decryption and must be kept secret by the receiver. RSA Algorithm is named after Ron Rivest, Adi Shamir and Leonard Adleman, who published the algorithm in 1977.

Example of Asymmetric Cryptography:

If Person A wants to send a message securely to Person B:

  • Person A encrypts the message using Person B’s Public Key.
  • Person B decrypts the message using their Private Key.

RSA Algorithm

RSA Algorithm is based on factorization of large number and modular arithmetic for encrypting and decrypting data. It consists of three main stages:

  1. Key Generation: Creating Public and Private Keys
  2. Encryption: Sender encrypts the data using Public Key to get cipher text.
  3. Decryption: Decrypting the cipher text using Private Key to get the original data.

1. Key Generation

  • Choose two large prime numbers, say p and q. These prime numbers should be kept secret.
  • Calculate the product of primes, n = p * q. This product is part of the public as well as the private key.
  • Calculate Euler Totient FunctionΦ(n) as Φ(n) = Φ(p * q) = Φ(p) * Φ(q) = (p – 1) * (q – 1).
  • Choose encryption exponent e, such that
    • 1 < e < Φ(n), and
    • gcd(e, Φ(n)) = 1, that is e should be co-prime with Φ(n).
  • Calculate decryption exponent d, such that

Finally, the Public Key = (n, e) and the Private Key = (n, d).

2. Encryption

To encrypt a message M, it is first converted to numerical representation using ASCII and other encoding schemes. Now, use the public key (n, e) to encrypt the message and get the cipher text using the formula:

C = Me mod n, where C is the Cipher text and e and n are parts of public key.

3. Decryption

To decrypt the cipher text C, use the private key (n, d) and get the original data using the formula:

M = Cd mod n, where M is the message and d and n are parts of private key.

Example of RSA Algorithm


Idea behind RSA Algorithm

The idea of RSA is based on the fact that it is difficult to factorize a large integer. The Public Key is (n, e), where n and e are publicly known, while the Private Key is (n, d). Since only the receiver knows the value of d, only they can decrypt the message. But is it possible to find the value of d using n and e?

We know that (d * e) ≡ 1 mod Φ(n), so if we can calculate the value of Φ(n), we can find the value of d. But Φ(n) = (p – 1) * (q – 1). So, we need the value of p and q. Now, one might think that it’s quite easy to find the value of p and q as n = p * q and n is already publicly known but RSA Algorithm takes the value of p and q to be very large which in turn makes the value of n extremely large and factorizing such a large value is computationally impossible.

Therefore encryption strength lies in the values of p and q. 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.

Note: If someone gets to know the value of p and q, then he can calculate the value of d and decrypt the message.

Implementation of RSA Algorithm

C++
// C++ Program for implementation of RSA Algorithm

#include <bits/stdc++.h>

using namespace std;

// Function to compute base^expo mod m
int power(int base, int expo, int m) {
    int res = 1;
    base = base % m;
    while (expo > 0) {
        if (expo & 1)
            res = (res * 1LL * base) % m;
        base = (base * 1LL * base) % m;
        expo = expo / 2;
    }
    return res;
}

// Function to find modular inverse of e modulo phi(n)
// Here we are calculating phi(n) using Hit and Trial Method
// but we can optimize it using Extended Euclidean Algorithm
int modInverse(int e, int phi) {
    for (int d = 2; d < phi; d++) {
        if ((e * d) % phi == 1)
            return d;
    }
    return -1;
}

// RSA Key Generation
void generateKeys(int &e, int &d, int &n) {
    int p = 7919;
    int q = 1009;
    
    n = p * q;
    int phi = (p - 1) * (q - 1);

    // Choose e, where 1 < e < phi(n) and gcd(e, phi(n)) == 1
    for (e = 2; e < phi; e++) {
        if (__gcd(e, phi) == 1)
            break;
    }

    // Compute d such that e * d ≡ 1 (mod phi(n))
    d = modInverse(e, phi);
}

// Encrypt message using public key (e, n)
int encrypt(int m, int e, int n) {
    return power(m, e, n);
}

// Decrypt message using private key (d, n)
int decrypt(int c, int d, int n) {
    return power(c, d, n);
}

int main() {
    int e, d, n;
    
    // Key Generation
    generateKeys(e, d, n);
  
    cout << "Public Key (e, n): (" << e << ", " << n << ")\n";
    cout << "Private Key (d, n): (" << d << ", " << n << ")\n";

    // Message
    int M = 123;
    cout << "Original Message: " << M << endl;

    // Encrypt the message
    int C = encrypt(M, e, n);
    cout << "Encrypted Message: " << C << endl;

    // Decrypt the message
    int decrypted = decrypt(C, d, n);
    cout << "Decrypted Message: " << decrypted << endl;

    return 0;
}
Java
// Java Program for implementation of RSA Algorithm

import java.math.BigInteger;

class GfG {

    // Function to compute base^expo mod m using BigInteger
    static BigInteger power(BigInteger base, BigInteger expo, BigInteger m) {
        return base.modPow(expo, m);
    }

    // Function to find modular inverse of e modulo phi(n)
    static BigInteger modInverse(BigInteger e, BigInteger phi) {
        return e.modInverse(phi);
    }

    // RSA Key Generation
    static void generateKeys(BigInteger[] keys) {
        BigInteger p = new BigInteger("7919");
        BigInteger q = new BigInteger("1009");
        
        BigInteger n = p.multiply(q);
        BigInteger phi = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));

        // Choose e, where 1 < e < phi(n) and gcd(e, phi(n)) == 1
        BigInteger e = BigInteger.ZERO;
        for (e = new BigInteger("2"); e.compareTo(phi) < 0; e = e.add(BigInteger.ONE)) {
            if (e.gcd(phi).equals(BigInteger.ONE)) {
                break;
            }
        }

        // Compute d such that e * d ≡ 1 (mod phi(n))
        BigInteger d = modInverse(e, phi);

        keys[0] = e;  // Public Key (e)
        keys[1] = d;  // Private Key (d)
        keys[2] = n;  // Modulus (n)
    }

    // Encrypt message using public key (e, n)
    static BigInteger encrypt(BigInteger m, BigInteger e, BigInteger n) {
        return power(m, e, n);
    }

    // Decrypt message using private key (d, n)
    static BigInteger decrypt(BigInteger c, BigInteger d, BigInteger n) {
        return power(c, d, n);
    }

    public static void main(String[] args) {
        BigInteger[] keys = new BigInteger[3]; // e, d, n
        
        // Key Generation
        generateKeys(keys);
      
        System.out.println("Public Key (e, n): (" + keys[0] + ", " + keys[2] + ")");
        System.out.println("Private Key (d, n): (" + keys[1] + ", " + keys[2] + ")");

        // Message
        BigInteger M = new BigInteger("123");
        System.out.println("Original Message: " + M);

        // Encrypt the message
        BigInteger C = encrypt(M, keys[0], keys[2]);
        System.out.println("Encrypted Message: " + C);

        // Decrypt the message
        BigInteger decrypted = decrypt(C, keys[1], keys[2]);
        System.out.println("Decrypted Message: " + decrypted);
    }
}
Python
# Python Program for implementation of RSA Algorithm

def power(base, expo, m):
    res = 1
    base = base % m
    while expo > 0:
        if expo & 1:
            res = (res * base) % m
        base = (base * base) % m
        expo = expo // 2
    return res

# Function to find modular inverse of e modulo phi(n)
# Here we are calculating phi(n) using Hit and Trial Method
# but we can optimize it using Extended Euclidean Algorithm
def modInverse(e, phi):
    for d in range(2, phi):
        if (e * d) % phi == 1:
            return d
    return -1

# RSA Key Generation
def generateKeys():
    p = 7919
    q = 1009
    
    n = p * q
    phi = (p - 1) * (q - 1)

    # Choose e, where 1 < e < phi(n) and gcd(e, phi(n)) == 1
    e = 0
    for e in range(2, phi):
        if gcd(e, phi) == 1:
            break

    # Compute d such that e * d ≡ 1 (mod phi(n))
    d = modInverse(e, phi)

    return e, d, n

# Function to calculate gcd
def gcd(a, b):
    while b != 0:
        a, b = b, a % b
    return a

# Encrypt message using public key (e, n)
def encrypt(m, e, n):
    return power(m, e, n)

# Decrypt message using private key (d, n)
def decrypt(c, d, n):
    return power(c, d, n)

# Main execution
if __name__ == "__main__":
    
    # Key Generation
    e, d, n = generateKeys()
  
    print(f"Public Key (e, n): ({e}, {n})")
    print(f"Private Key (d, n): ({d}, {n})")

    # Message
    M = 123
    print(f"Original Message: {M}")

    # Encrypt the message
    C = encrypt(M, e, n)
    print(f"Encrypted Message: {C}")

    # Decrypt the message
    decrypted = decrypt(C, d, n)
    print(f"Decrypted Message: {decrypted}")
JavaScript
// JavaScript Program for implementation of RSA Algorithm

// Function to compute base^expo mod m using BigInt
function power(base, expo, m) {
    let res = BigInt(1); 
    base = BigInt(base) % BigInt(m); 
    while (expo > 0) {
        if (expo & BigInt(1)) {
            res = (res * base) % BigInt(m);
        }
        base = (base * base) % BigInt(m); 
        expo = Math.floor(Number(expo) / 2);
        expo = BigInt(expo);
    }
    return res;
}

// Function to find modular inverse of e modulo phi(n)
function modInverse(e, phi) {
    e = BigInt(e);
    phi = BigInt(phi);
    for (let d = BigInt(2); d < phi; d++) {
        if ((e * d) % phi === BigInt(1)) {
            return d;
        }
    }
    return -1;
}

// RSA Key Generation
function generateKeys() {
    let p = BigInt(7919);  
    let q = BigInt(1009);

    let n = p * q;
    let phi = (p - BigInt(1)) * (q - BigInt(1));

    // Choose e, where 1 < e < phi(n) and gcd(e, phi(n)) == 1
    let e;
    for (e = BigInt(2); e < phi; e++) {
        if (gcd(e, phi) === BigInt(1))
            break;
    }

    // Compute d such that e * d ≡ 1 (mod phi(n))
    let d = modInverse(e, phi);
    return { e, d, n };
}

function gcd(a, b) {
    while (b !== BigInt(0)) {
        let t = b;
        b = a % b;
        a = t;
    }
    return a;
}

// Encrypt message using public key (e, n)
function encrypt(m, e, n) {
    return power(m, e, n);
}

// Decrypt message using private key (d, n)
function decrypt(c, d, n) {
    return power(c, d, n);
}

// Key Generation
let { e, d, n } = generateKeys();

console.log(`Public Key (e, n): (${e}, ${n})`);
console.log(`Private Key (d, n): (${d}, ${n})`);

// Message
let M = 123;
console.log(`Original Message: ${M}`);

// Encrypt the message
let C = encrypt(M, e, n);
console.log(`Encrypted Message: ${C}`);

// Decrypt the message
let decrypted = decrypt(C, d, n);
console.log(`Decrypted Message: ${decrypted}`);

Output
Public Key (e, n): (5, 7990271)
Private Key (d, n): (1596269, 7990271)
Original Message: 123
Encrypted Message: 3332110
Decrypted Message: 123

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.
  • 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.

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.

Dreaming of M.Tech in IIT? Get AIR under 100 with our GATE 2026 CSE & DA courses! Get flexible weekday/weekend options, live mentorship, and mock tests. Access exclusive features like All India Mock Tests, and Doubt Solving—your GATE success starts now!


Next Article

Similar Reads

Custom Building Cryptography Algorithms (Hybrid Cryptography)
Cryptography can be defined as an art of encoding and decoding the patterns (in the form of messages). Cryptography is a very straightforward concept which deals with manipulating the strings (or text) to make them unreadable for the intermediate person. It has a very effective way to encrypt or decrypts the text coming from the other parties. Some
15+ min read
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 p and q Lets take p = 3 and q = 11 Step-2: Compute the value of n and \phi It is gi
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
How to generate Large Prime numbers for RSA Algorithm
The security of the RSA algorithm is based on the difficulty of factorizing very large numbers. The setup of an RSA cryptosystem involves the generation of two large primes, say p and q, from which, the RSA modulus is calculated as n = p * q. The greater the modulus size, the higher is the security level of the RSA system. The recommended RSA modul
15 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
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
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