Friday, October 25, 2013

TO IMPLEMENT RSA ENCRYPTION ALGORITHM IN JAVA

/*

TITLE: TO IMPLEMENT RSA ENCRYPTION ALGORITHM IN JAVA
RSA.JAVA
*/
import java.util.*;
import java.io.*;
class RSA
{
         public static void main(String args[])
{
double i=0,e=0;

double p=7,q=11,n=p*q,fi=(p-1)*(q-1);
System.out.print("\nThe two prime numbers are :");
System.out.print("\np= "+p+"\tq= "+q);
System.out.print("\nn=p*q= "+n);
System.out.print("\nfi(n)= "+fi);
CoPrime c=new CoPrime();

for(i=2;!c.coprime(fi,i)&&i<fi;i++)
{
e=i;
}
e=13;
System.out.print("\n\nGenerated e= "+e);
double d=0;
while(!((e*d)%fi==1))
{
d++;
}
System.out.print("\n\nd="+d);

System.out.print("\n\n\nPublic Key= (" + e + " , " + n + ")");
System.out.print("\nPrivate Key= (" + d + ")");


System.out.print("\n\nEnter the plaintext: ");
Scanner in=new Scanner(System.in);
int plaintext=in.nextInt();
double C=Math.pow(plaintext,e)%n;
System.out.print("CipherText= "+C);


System.out.print("\n\n\nRECEIVER");

System.out.print("\nEnter the CipherText: ");
double Ci=in.nextDouble();
double m=1;
for(i=0;i<d;i++)
m=m*Ci%n;
m=m%n;
System.out.println("\nPlaintext= "+m);
}
}
class CoPrime
{
double hcf(double a,double h)
{
double temp;
while(true)
{
temp=a%h;
if(temp==0)
return h;
a=h;
h=temp;
}
}

boolean coprime(double c,double d)
{
double gcd=hcf(c,d);
if(gcd==1)
return true;

return false;
}
}
/*
OUTPUT:
The two prime numbers are :
p= 7.0  q= 11.0
n=p*q= 77.0
fi(n)= 60.0

Generated e= 13.0

d=37.0


Public Key= (13.0 , 77.0)
Private Key= (37.0)

Enter the plaintext: 9
CipherText= 58.0


RECEIVER
Enter the CipherText: 58

Plaintext= 9.0
*/

No comments:

Post a Comment