Java Program to Implement the RSA Algorithm

This is a java program to implement RSA algorithm. RSA is one of the first practicable public-key cryptosystems and is widely used for secure data transmission. In such a cryptosystem, the encryption key is public and differs from the decryption key which is kept secret. In RSA, this asymmetry is based on the practical difficulty of factoring the product of two large prime numbers, the factoring problem. RSA stands for Ron Rivest, Adi Shamir and Leonard Adleman.

Here is the source code of the Java Program to Implement the RSA Algorithm. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

package com.maixuanviet.setandstring;
 
import java.io.DataInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Random;
 
public class RSA
{
    private BigInteger p;
    private BigInteger q;
    private BigInteger N;
    private BigInteger phi;
    private BigInteger e;
    private BigInteger d;
    private int        bitlength = 1024;
    private Random     r;
 
    public RSA()
    {
        r = new Random();
        p = BigInteger.probablePrime(bitlength, r);
        q = BigInteger.probablePrime(bitlength, r);
        N = p.multiply(q);
        phi = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
        e = BigInteger.probablePrime(bitlength / 2, r);
        while (phi.gcd(e).compareTo(BigInteger.ONE) > 0 && e.compareTo(phi) < 0)
        {
            e.add(BigInteger.ONE);
        }
        d = e.modInverse(phi);
    }
 
    public RSA(BigInteger e, BigInteger d, BigInteger N)
    {
        this.e = e;
        this.d = d;
        this.N = N;
    }
 
    @SuppressWarnings("deprecation")
    public static void main(String[] args) throws IOException
    {
        RSA rsa = new RSA();
        DataInputStream in = new DataInputStream(System.in);
        String teststring;
        System.out.println("Enter the plain text:");
        teststring = in.readLine();
        System.out.println("Encrypting String: " + teststring);
        System.out.println("String in Bytes: "
                + bytesToString(teststring.getBytes()));
        // encrypt
        byte[] encrypted = rsa.encrypt(teststring.getBytes());
        // decrypt
        byte[] decrypted = rsa.decrypt(encrypted);
        System.out.println("Decrypting Bytes: " + bytesToString(decrypted));
        System.out.println("Decrypted String: " + new String(decrypted));
    }
 
    private static String bytesToString(byte[] encrypted)
    {
        String test = "";
        for (byte b : encrypted)
        {
            test += Byte.toString(b);
        }
        return test;
    }
 
    // Encrypt message
    public byte[] encrypt(byte[] message)
    {
        return (new BigInteger(message)).modPow(e, N).toByteArray();
    }
 
    // Decrypt message
    public byte[] decrypt(byte[] message)
    {
        return (new BigInteger(message)).modPow(d, N).toByteArray();
    }
}

Output:

$ javac RSA.java
$ java RSA
 
Enter the plain text:
MaiXuanViet
Encrypting String: MaiXuanViet
String in Bytes: 8397110102111117110100114121
Decrypting Bytes: 8397110102111117110100114121
Decrypted String: MaiXuanViet

Related posts:

Java Program to Implement IdentityHashMap API
Java Program to Perform Cryptography Using Transposition Technique
Java Program to Find the Shortest Path from Source Vertex to All Other Vertices in Linear Time
Java 8 – Powerful Comparison with Lambdas
Basic Authentication with the RestTemplate
Java Program to Implement Circular Singly Linked List
Build a REST API with Spring and Java Config
Java Program to Perform integer Partition for a Specific Case
Java Program to Check whether Graph is a Bipartite using BFS
Java Program to Implement Threaded Binary Tree
Control Structures in Java
Java Program to Implement Wagner and Fisher Algorithm for online String Matching
Introduction to the Java NIO2 File API
Number Formatting in Java
New Features in Java 9
ThreadPoolTaskExecutor corePoolSize vs. maxPoolSize
JUnit 5 for Kotlin Developers
Java Program to Implement Max-Flow Min-Cut Theorem
XML-Based Injection in Spring
Checked and Unchecked Exceptions in Java
Java Program to Implement the Program Used in grep/egrep/fgrep
Interface trong Java 8 – Default method và Static method
Spring Boot - Enabling Swagger2
Java Program to Implement a Binary Search Algorithm for a Specific Search Sequence
Java Program to Implement Binary Search Tree
Spring @Primary Annotation
Java Program to Implement Stack using Linked List
Sử dụng JDBC API thực thi câu lệnh truy vấn dữ liệu
Call Methods at Runtime Using Java Reflection
Java List UnsupportedOperationException
Simple Single Sign-On with Spring Security OAuth2
Java Program to Find Basis and Dimension of a Matrix