import javax.swing.JOptionPane;
import java.math.BigInteger;
import java.util.Random;


public class TestBigIntegerRSA {
    public TestBigIntegerRSA() {
        Random rnd = new Random();
        while(true) {
            String input = JOptionPane.showInputDialog("Enter number of bits for primes","16");
            if( input == null ) return;
            int numBits = Integer.parseInt(input);
            BigInteger p = BigInteger.probablePrime(numBits,rnd);
            BigInteger pm1 = p.subtract(BigInteger.ONE);
            BigInteger q = BigInteger.probablePrime(numBits,rnd);
            while( q.equals(p) ) q = BigInteger.probablePrime(numBits,rnd);
            BigInteger qm1 = q.subtract(BigInteger.ONE);
            BigInteger n = p.multiply(q);
            BigInteger rel1 = new BigInteger("2");
            BigInteger rel2 = new BigInteger("2");
            BigInteger e = null;
            while( rel1.compareTo(BigInteger.ONE) != 0 || rel2.compareTo(BigInteger.ONE) != 0 ) {
                String exp = JOptionPane.showInputDialog("Enter e relatively prime to "+ (pm1) +" and " + (qm1),"11");
                if( exp == null ) return;
                e = new BigInteger(exp);
                rel1 = e.gcd(pm1);
                rel2 = e.gcd(qm1);
                System.out.println(rel1 + " " + rel2);
            } // end while
            BigInteger d = e.modInverse(pm1.multiply(qm1));
            JOptionPane.showMessageDialog(null,"p = " + p+", q = "+q+", n = "+n+", e = "+e+" and d = "+d);
            while(true) {
                String message = JOptionPane.showInputDialog("Enter message","65");
                if( message == null ) break;
                BigInteger m = new BigInteger(message);
                BigInteger c = m.modPow(e,n);
                JOptionPane.showMessageDialog(null,"Coded message is "+c);
                BigInteger m1 = c.modPow(d,n);
                JOptionPane.showMessageDialog(null,"Message = " + m+ "\nCoded message is "+c+"\nDecoded message is "+m1);
            } // end while
        } // end while
    }
    
    public static void main(String[] a) {
        new TestBigIntegerRSA();
        System.exit(0);
    } // end main
    
}
