Answer:
Check the explanation
Step-by-step explanation:
Below is the Java code with output screenshots
Code :
import java.io.DataInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Random;
public class RSAImplement
{
private BigInteger p; // p and q are two prime numbers
private BigInteger q;
private BigInteger N; // n = p*q
private BigInteger phi; // phi = (p-1)*(q-1)
private BigInteger e; // e is a relative prime number where 1<e<phi
private BigInteger d; //private key - (d*e mod phi = 1)
private int bitlength = 1024;
private Random r;
// public key = (n,e)
public RSAImplement()
{
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 RSAImplement(BigInteger e, BigInteger d, BigInteger N)
{
this. e = e;
this. d = d;
this. N = N;
}
public static void main(String[] args) throws IOException
{
RSAImplement rsaImplement = new RSAImplement();
DataInputStream in = new DataInputStream(System.in);
String teststring;
System.out.println("Enter the message you want to send :");
teststring = in. readLine();
System.out.println("Encrypting Message: " + teststring);
System.out.println("Message in Bytes: "
+ bytesToString(teststring.getBytes()));
// encryptMessage
byte[] encrypted = rsaImplement. encryptMessage(teststring. getBytes());
// decryptMessage
byte[] decrypted = rsaImplement. decryptMessage(encrypted);
System.out.println("Decrypting Bytes: " + bytesToString(decrypted));
System.out.println("Decrypted Message: " + new String(decrypted));
}
private static String bytesToString(byte[] encrypted)
{
String test = "";
for (byte b : encrypted)
{
test += Byte. toString(b);
}
return test;
}
// method which Encrypt message
public byte[] encryptMessage(byte[] message)
{
return (new BigInteger(message)).modPow(e, N). toByteArray();
}
// method which Decrypt message
public byte[] decryptMessage(byte[] message)
{
return (new BigInteger(message)).modPow(d, N). toByteArray();
}
}
Kindly check the attached image below for the code output.