Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Cryptography Cryptography Tutorial Java Java and Cryptography Mastery Series Module 4 - Asymmetric Cryptography

Java Program for RSA Encryption and Decryption from Scratch

Reviewed & accurate
AI Summary

Introduction

RSA, named after its inventors Ron Rivest, Adi Shamir, and Leonard Adleman, was first published in 1977 in the paper "A Method for Obtaining Digital Signatures and Public-Key Cryptosystems". The trio had been working at MIT on a problem that Whitfield Diffie and Martin Hellman had just opened up the year before: how to do encryption without first exchanging a shared secret. In this rsa encryption java tutorial we will implement the algorithm from scratch using only Java's BigInteger class, with no external libraries.

RSA was the first practical public-key cryptosystem and remains the backbone of internet security today. Almost every HTTPS certificate, every SSH key, every signed Docker image, and every JWT signed with RS256 uses RSA. The security rests on the hardness of factoring the product of two large prime numbers. As of 2024, the largest publicly factored RSA modulus was 768 bits long; keys below 2048 bits are now considered unsafe. NIST recommends 3072-bit keys for protection beyond 2030.

What is RSA?

RSA is an asymmetric cryptosystem. Asymmetric means the key used to encrypt is different from the key used to decrypt. Each user has a public key that they can publish openly, and a private key that they must keep secret. Anyone can encrypt a message to a user with that user's public key; only the user can decrypt it with their private key.

The key generation process picks two large random primes p and q, multiplies them to get the modulus n = p * q, then picks a public exponent e that is coprime to (p-1)*(q-1). The private exponent d is the modular inverse of e modulo (p-1)*(q-1). The public key is the pair (n, e). The private key is the pair (n, d).

Encryption is the function c = m^e mod n, where m is the plaintext integer and c is the ciphertext integer. Decryption is m = c^d mod n. The mathematical miracle is that for any m, raising m to the power e mod n and then raising the result to the power d mod n recovers m. This works because of Fermat's Little Theorem and the Chinese Remainder Theorem.

Compared to symmetric ciphers like AES, RSA is much slower and can only encrypt a small message (up to the size of the modulus minus padding). Real systems use RSA only to wrap a symmetric key, then use AES for the actual data. This is called hybrid encryption.

How RSA Works Step by Step

Let us walk through a toy RSA with very small numbers to see the math exactly. Pick p = 61 and q = 53. These are too small for real security but easy to verify by hand.

Step 1: Compute the modulus n = p * q = 61 * 53 = 3233.

Step 2: Compute Euler's totient phi = (p - 1) * (q - 1) = 60 * 52 = 3120.

Step 3: Pick a public exponent e coprime to phi. The common choice is e = 17, which divides no factor of 3120.

Step 4: Compute the private exponent d as the modular inverse of e mod phi, meaning d * e mod phi = 1. Solving 17 * d mod 3120 = 1 gives d = 2753. (You can verify: 17 * 2753 = 46801, and 46801 mod 3120 = 1.)

Step 5: Public key is (n=3233, e=17). Private key is (n=3233, d=2753).

Step 6: To encrypt m = 65 (the ASCII for 'A'), compute c = m^e mod n = 65^17 mod 3233 = 2790.

Step 7: To decrypt, compute m = c^d mod n = 2790^2753 mod 3233 = 65. The original message is recovered.

Java Program for RSA Encryption and Decryption from Scratch

import java.math.BigInteger;
import java.security.SecureRandom;

public class RsaDemo {

    static class KeyPair {
        BigInteger n, e, d;
        KeyPair(BigInteger n, BigInteger e, BigInteger d) {
            this.n = n; this.e = e; this.d = d;
        }
    }

    public static KeyPair generate(int bitLength) {
        SecureRandom rng = new SecureRandom();
        BigInteger p = BigInteger.probablePrime(bitLength / 2, rng);
        BigInteger q = BigInteger.probablePrime(bitLength / 2, rng);
        BigInteger n = p.multiply(q);
        BigInteger phi = p.subtract(BigInteger.ONE)
                            .multiply(q.subtract(BigInteger.ONE));
        BigInteger e = BigInteger.valueOf(65537); // common public exponent
        BigInteger d = e.modInverse(phi);
        return new KeyPair(n, e, d);
    }

    public static BigInteger encrypt(BigInteger m, KeyPair key) {
        return m.modPow(key.e, key.n);
    }

    public static BigInteger decrypt(BigInteger c, KeyPair key) {
        return c.modPow(key.d, key.n);
    }

    public static void main(String[] args) {
        KeyPair key = generate(1024); // 1024-bit toy RSA; use 3072 in real life
        System.out.println("Modulus n : " + key.n);
        System.out.println("Public e  : " + key.e);
        System.out.println("Private d : " + key.d);

        String message = "Hi";
        BigInteger m = new BigInteger(message.getBytes());
        System.out.println("Plaintext int: " + m);

        BigInteger c = encrypt(m, key);
        System.out.println("Ciphertext   : " + c);

        BigInteger recovered = decrypt(c, key);
        System.out.println("Decrypted int: " + recovered);
        byte[] bytes = recovered.toByteArray();
        System.out.println("Decrypted txt: " + new String(bytes));
    }
}

Code Explanation Line by Line

The generate method picks two random primes using BigInteger.probablePrime. This is a static factory that uses Miller-Rabin primality testing to produce a value that is almost certainly prime. We pass half the requested key length so that p and q are each roughly half as many bits as the modulus n. Multiplying two half-size primes gives a modulus of roughly the full size.

Euler's totient phi is computed as (p-1) * (q-1). This is the order of the multiplicative group of integers modulo n. The security of RSA depends on an attacker not knowing phi, which requires factoring n. We pick e = 65537 because it is the de facto standard public exponent: it is large enough to defeat certain low-exponent attacks and small enough to make encryption fast (its binary form is 10000000000000001, so exponentiation uses only two multiplications).

The private exponent d is computed with e.modInverse(phi). This is the BigInteger method for finding the modular inverse, that is, the value d such that e * d mod phi = 1. The modInverse method uses the extended Euclidean algorithm internally.

Encryption and decryption each take one line: m.modPow(key.e, key.n) and c.modPow(key.d, key.n). The modPow method uses square-and-multiply to raise a BigInteger to a power modulo another BigInteger efficiently. Even a 3072-bit RSA exponentiation takes only a few milliseconds on a modern CPU.

The main method generates a 1024-bit toy RSA key (real systems use 3072 bits), then encrypts the two-byte string "Hi" by converting it to a BigInteger with new BigInteger(bytes). Note that the message must be smaller than the modulus, otherwise encryption will lose information. After decryption we convert the recovered BigInteger back to bytes with toByteArray and rebuild the original string.

Sample Input and Output

Modulus n : 96893... (very long number)
Public e  : 65537
Private d : 53841... (very long number)
Plaintext int: 26985
Ciphertext   : 48213... (large number)
Decrypted int: 26985
Decrypted txt: Hi

The exact modulus and ciphertext will differ every run because the primes are randomly chosen. The crucial fact is that the decrypted text exactly matches the original input, which proves the implementation is correct.

Common Mistakes to Avoid

First, never use textbook RSA directly on a message. Textbook RSA is deterministic, so encrypting the same message twice produces the same ciphertext, which lets an attacker verify a guessed plaintext. Always use a padding scheme such as OAEP (Optimal Asymmetric Encryption Padding), which adds random bytes and a checksum.

Second, never use a small exponent such as e = 3 without padding. If you encrypt the same plaintext to three different recipients who all use e = 3, an attacker can recover the plaintext by the Chinese Remainder Theorem. The use of e = 65537 with OAEP avoids this.

Third, never use a key smaller than 3072 bits for new applications. 2048-bit keys are still acceptable for short-term use but should be migrated. 1024-bit keys were factored experimentally in 2003 and are considered insecure.

Fourth, never sign a message directly with the private key. Always hash the message first and sign the hash, using a padding scheme such as PSS for signatures. Otherwise you expose yourself to chosen-plaintext attacks.

Real-World Applications

RSA is the public-key workhorse of the internet. HTTPS uses RSA to sign certificates and, in older TLS versions, to encrypt the symmetric key. SSH uses RSA as one of several supported key types. JWT supports RS256, which is RSA signing with SHA-256. Code signing on Android and Windows often uses RSA. S/MIME email signing uses RSA. PGP and GnuPG use RSA extensively.

For new high-security applications, elliptic-curve cryptography (ECDSA and Ed25519) is preferred because it offers the same security with much shorter keys and faster operations.

Conclusion

In this rsa encryption java tutorial we built the entire RSA cryptosystem from scratch using only BigInteger and SecureRandom. We walked through every step of the math, ran a 1024-bit toy example, and saw the round trip recover the original plaintext. For real applications, use Java's built-in KeyPairGenerator.getInstance("RSA") with OAEP padding rather than this toy code, but the math you have learned is exactly what runs under the hood.

Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments