11.
Write a program for simple RSA algorithm to encrypt and decrypt
the data
import java.util.Scanner;
public class rsa {
static int encrypt(int M,int e,int n)
{
int k=1,i;
for(i=1;i<=e;i++)
{
k=(k*M)%n;
}
return k;
static int gcd(int z, int e)
{
int k;
while(true)
{
k=z%e;
z=e;
e=k;
if(k==1)
return 1;
else if(k==0)
return 0;
}
}
public static void main(String[] args) {
Scanner t;
int p,q,n,z,e,k=1,d,i;
int ci[]=new int[20];
int in[]=new int[20];
t=new Scanner(System.in);
System.out.println("\n Enter the prime numbers p and q\n");
p=t.nextInt();
q=t.nextInt();
n=p*q;
z=(p-1)*(q-1);
do{
System.out.println("\n Enter the random number b/w 3 and z\n\n");
e=t.nextInt();
}while((gcd(z,e)==0)&&e<(z-1));
System.out.println("\n Public Key Pair {%d,%d}\n",e,n);
for(k=1;((k*e)%z)!=1;k++) { }
System.out.println("\n the Private key pair {%d,%d}\n\n",k,n);
System.out.println(" \n Enter the message in decimal\n");
t=new Scanner(System.in);
for(i=0;i<1;i++)
in[i]=t.nextInt();
for(i=0;i<1;i++)
ci[i]=encrypt(in[i],e,n);
System.out.println("\n cipher text is : ");
for(i=0;i<1;i++)
System.out.println("\n %d\t",ci[i]);
System.out.println("\n The plain text is : \n");
for(i=0;i<1;i++)
System.out.println("\n %d\t",(encrypt(ci[i],k,n)));
}
}
OUTPUT
Enter the prime numbers p and q
5 11
Enter the random number b/w 3 and z
Public Key Pair {3,55}
the private key pair {27,55}
Enter the message in decimal
24
cipher text is :
19
The plain text is :
24