Write a Java program to implement RSA Algoithm | RSA Algorithm in Java | Cryptography


HARDWARE AND SOFTWARE REQUIREMENT:
1. Intel based Desktop PC: - RAM of 512 MB
2. Notepad/Notepad ++ editor  and Command Prompt or
3. IntelliJ IDEA Community Edition/ Eclipse

THEORY:

Ø  RSA is an encryption algorithm, in order to have secure transmission of  messages over the internet.
Ø  Many protocols like Secure ShellS/MIME, and SSL/TLS are based on RSA for encryption and digital signature functions.
Ø  It is an asymmetric encryption technique [Asymmetric means that there are two different keys i.e. Public key and Private key. That’s why it is also known as public key cryptography].
Ø  The public key is used to encrypt messages and can be known to everyone; Messages encrypted using the public key can only be decrypted with the private key / Secret key.

An example of asymmetric cryptography in Client-Server Communication:

1.       A client (web browser) sends its shared key to the  web server and requests for some data.
2.     The server encrypts the data using client’s shared key and sends the encrypted data.
3.     Client receives this data and decrypts it with the help of secret key.

Encrypting message:

Ø  The encryption with the help of public key e  is done by using following formula                     
                                                c = me mod n    

Decrypting message

Ø  The decryption of ciphertext with the help of  private key {\displaystyle d\,}d  in the following procedure:
{\displaystyle m=c^{d}{\bmod {n}}}                              m = cd mod n
SOURCE CODE:

import java.math.*;
import java.util.Random;
import java.util.Scanner;

public class RSA {
    static Scanner sc = new Scanner(System.in);
    public static void main(String[ ]args) {
        System.out.print("Enter a Prime number: ");
        BigInteger p=sc.nextBigInteger(); //Here's one prime number..
        System.out.print("Enter another prime number: ");
        BigInteger q=sc.nextBigInteger(); //..and another.
        BigInteger n=p.multiply(q);
        BigInteger n2=p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
        BigInteger e = generateE(n2);
        BigInteger d = e.modInverse(n2); // Here's the multiplicative inverse
        System.out.println("Encryption keys are: " + e + ", " + n);
        System.out.println("Decryption keys are: " + d + ", " + n);
    }

    private static BigInteger generateE(BigInteger fiofn){
        int y, intGCD;

        Random x = new Random();
        BigInteger e;

        do{
            y= x.nextInt(fiofn.intValue()-1);
            String z = Integer.toString(y);
            e = new BigInteger(z);
            BigInteger gcd = fiofn.gcd(e);
            intGCD = gcd.intValue();
        }

        while(y<=2 || intGCD!=1);
        return e;
    }
}

OUTPUT:

Comments

Post a Comment

Search related post on google