9. Develop a program for simple RSA algorithm to encrypt and decrypt the data.
import [Link];
import [Link];
import [Link];
import [Link];
public class RSA {
private BigInteger p,q,N,phi,e,d;
private int bitlength=1024;
private Random r;
public RSA()
{
r=new Random();
p=[Link](bitlength,r);
q=[Link](bitlength,r);
[Link]("Prime number p is"+p);
[Link]("prime number q is"+q);
N=[Link](q);
phi=[Link]([Link]).multiply([Link]([Link]));
e=[Link](bitlength/2,r);
while([Link](e).compareTo([Link])>0&&[Link](phi)<0)
{
[Link]([Link]);
}
[Link]("Public key is"+e); d=[Link](phi);
[Link]("Private key is"+d);
}
public RSA(BigInteger e,BigInteger d,BigInteger N)
{
this.e=e;
this.d=d;
this.N=N;
}
public static void main(String[] args)throws IOException
{
RSA rsa=new RSA();
DataInputStream in=new DataInputStream([Link]);
String testString; [Link]("Enter the plain text:");
testString=[Link]();
[Link]("Encrypting string:"+testString);
[Link]("string in bytes:"+bytesToString([Link]()));
byte[] encrypted=[Link]([Link]());
byte[] decrypted=[Link](encrypted);
[Link]("Dcrypting Bytes:"+bytesToString(decrypted));
[Link]("Dcrypted string:"+new String(decrypted));
}
private static String bytesToString(byte[] encrypted)
{
String test=" "; for(byte b:encrypted)
{
test+=[Link](b);
}
return test;
}
public byte[]encrypt(byte[]message)
{
return(new BigInteger(message)).modPow(e,N).toByteArray();
}
public byte[]decrypt(byte[]message)
{
return(new BigInteger(message)).modPow(d,N).toByteArray();
}
}