Java program for simple RSA algorithm to encrypt and decrypt the data

The RSA algorithm can be used for both public key encryption and digital signatures. Its security is based on the difficulty of factoring large integers.
The RSA algorithm’s efficiency requires a fast method for performing the modular exponentiation operation. A less efficient, conventional method includes raising a number (the input) to a power (the secret or public key of the algorithm, denoted e and d, respectively) and taking the remainder of the division with N. A straight-forward implementation performs these two steps of the operation sequentially: first, raise it to the power and second, apply modulo

				
					Source Code:
import java.util.*;
import java.io.*;
public class rsa
{ static int gcd(int m,int n)
{ while(n!=0)
{ int r=m%n;
m=n;
n=r;
}
return m;
}

public static void main(String args[])
{
int p=0,q=0,n=0,e=0,d=0,phi=0;
int nummes[]=new int[100];
int encrypted[]=new int[100];
int decrypted[]=new int[100];
int i=0,j=0,nofelem=0;
Scanner sc=new Scanner(System.in);
String message ;
System.out.println("Enter the Message tobe encrypted:");
message= sc.nextLine();
System.out.println("Enter value of p and q\n");
p=sc.nextInt();
q=sc.nextInt();
n=p*q;
phi=(p-1)*(q-1);
for(i=2;i
if(gcd(i,phi)==1) break;
e=i;
for(i=2;i
if((e*i-1)%phi==0)
break;
d=i;
for(i=0;i
{
char c = message.charAt(i);
int a =(int)c;
nummes[i]=c-96;
}
nofelem=message.length();
for(i=0;i
{
encrypted[i]=1;
for(j=0;j
encrypted[i] =(encrypted[i]*nummes[i])%n;
}
System.out.println("\n Encrypted message\n");
for(i=0;i
{
System.out.print(encrypted[i]);
System.out.print((char)(encrypted[i]+96));
}
for(i=0;i
{ decrypted[i]=1;
for(j=0;j

decrypted[i]=(decrypted[i]*encrypted[i])%n;
}
System.out.println("\n Decrypted message\n ");
for(i=0;i
System.out.print((char)(decrypted[i]+96));
return;
}
}

				
			
********************************************************

Enter the text:
hello
Enter the value of P and Q :
5
7
Encrypted Text is: 8 h 10 j 17 q 17 q 15 o
Decrypted Text is: hello

Leave a Reply