import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.KeyPair;
import java.security.PublicKey;
import java.security.PrivateKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.math.BigInteger;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;

public class GenerateRSAPublicPrivateKeyPair {
    
    public GenerateRSAPublicPrivateKeyPair() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        SecureRandom secRnd = new SecureRandom();
        keyGen.initialize(512,secRnd);
        KeyPair keys = keyGen.generateKeyPair();
        PrivateKey privKey = keys.getPrivate();
        PublicKey pubKey = keys.getPublic();
        ObjectOutputStream privOut = new ObjectOutputStream(new FileOutputStream("BillsRSAPrivateKey"));
        privOut.writeObject(privKey);
        privOut.close();
        PrintWriter pubOut = new PrintWriter(new FileWriter("BillsRSAPublicKey"));
        BigInteger modulus = ((RSAPublicKey)pubKey).getModulus();
        BigInteger publicExponent = ((RSAPublicKey)pubKey).getPublicExponent();
        pubOut.println(modulus);
        pubOut.println(publicExponent);
        pubOut.close();
        BigInteger privateExponent = ((RSAPrivateKey)privKey).getPrivateExponent();
        String out = "\n\n Modulus = " + modulus;
        out += "\n\n Public exponent = " + publicExponent;
        out += "\n\n Private exponent = " + privateExponent;
        JTextArea outArea = new JTextArea(out,30,60);
        JOptionPane.showMessageDialog(null,new JScrollPane(outArea));
    } // end GenerateRSAPublicPrivateKeyPair
    
    public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
        new GenerateRSAPublicPrivateKeyPair();
        System.exit(0);
    } // end main
    
} // end GenerateRSAPublicPrivateKeyPair
