import java.math.*; import java.util.*; import java.io.*; public class rsatest { private static BigInteger one=new BigInteger("1"); public static String BigIntegerToString(BigInteger n) { return new String(n.toByteArray()); } public static BigInteger StringToBigInteger(String s) { return new BigInteger(s.getBytes()); } public static void main(String[] args) { BigInteger p, q, n, phi, phiminusone, d, e, msg, code, decode; Random r=new Random(System.currentTimeMillis()); InputStreamReader ISRin=new InputStreamReader(System.in); BufferedReader in=new BufferedReader(ISRin); String s, inp; p=new BigInteger(20,40,r); System.out.println(" p = "+p); q=new BigInteger(20,40,r); System.out.println(" q = "+q); n=p.multiply(q); System.out.println(" n = "+n); phi=p.subtract(one).multiply(q.subtract(one)); System.out.println(" phi = "+phi); phiminusone=phi.subtract(one); System.out.println(" phi-1 = "+phiminusone); d=new BigInteger(18,40,r); System.out.println(" d = "+d); e=d.modInverse(phi); System.out.println(" e = "+e); System.out.println(""); System.out.println(" Private key is ("+n+","+d+")"); System.out.println(" Public key is ("+n+","+e+")"); System.out.println(""); while (true) { System.out.print("Message: "); try { inp=in.readLine(); } catch (Exception ee) { break; } if (inp.equals("")) break; while (!inp.equals("")) { if (inp.length()>4) { s=inp.substring(0,4); inp=inp.substring(4); } else { s=inp; inp=""; } msg=StringToBigInteger(s); System.out.println(" message \""+s+"\"="+msg); code=msg.modPow(d,n); System.out.print(" "); System.out.println("encrypted: "+code); decode=code.modPow(e,n); s=BigIntegerToString(decode); System.out.println("decrypted \""+s+"\"="+decode); System.out.println(""); } } } }