for example: not working when prime nos are 7 and 13.. and when data is 36.
/* Algorithm: Choose p = 3 and q = 11 Compute n = p * q = 3 * 11 = 33 Compute f(n) = (p - 1) * (q - 1) = 2 * 10 = 20 Choose e such that 1 < e < f(n) and e and n are coprime. Let e = 7 Compute a value for d such that (d * e) % f(n) = 1. One solution is d = 3 [(3 * 7) % 20 = 1] Public key is (e, n) => (7, 33) Private key is (d, n) => (3, 33) The encryption of m = 2 is c = 27 % 33 = 29 The decryption of c = 29 is m = 293 % 33 = 2 */ import java.io.*; public class RSA { public static void main(String args[]) throws IOException { BufferedReader buff=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter 1st prime nos:"); int p=Integer.parseInt(buff.readLine()); System.out.println("Enter 2nd prime nos:"); int q=Integer.parseInt(buff.readLine()); //prime boolean flag=true; boolean p_true=check(p,flag); boolean q_true=check(q,flag); if((p_true==true) && (q_true==true)) { System.out.println("Nos are prime"); } else { System.out.println("Nos are not prime"); } int n=p*q; int N=((p-1)*(q-1)); int e=2; for(int i=2;i<N;i++) { if((N%i)!=0) {e=i;break;} else {continue; } }System.out.println("e="+e); int d; for(int i=1;;i++) { if(((i*e)%N)==1) { d=i; break;} else continue; } System.out.println("d="+d); System.out.println("Enter data to be encrypted"); int data=Integer.parseInt(buff.readLine()); int encrypt_data=(((int)Math.pow(data,e))%n); System.out.println("encrypted data"+encrypt_data); int decrypt_data=(((int)Math.pow(encrypt_data,d))%n); System.out.println("decrypted data"+decrypt_data); } public static boolean check(int p, boolean flag) { flag=true; for(int i=2;i<p;i++) { if(p%i!=0) continue; else {flag=false; break;} }return flag; } }