/** Generates a encrypted private key and certificate request. */ public static void genCertificateRequest( String dname, String emailAddressOfCA, String password, String privKeyLoc, String certLoc, String certReqLoc) throws Exception { String sigAlgName = "MD5WithRSA"; String keyAlgName = "RSA"; CertUtil.init(); // Generate a new key pair. KeyPairGenerator keygen = KeyPairGenerator.getInstance(keyAlgName); KeyPair keyPair = keygen.genKeyPair(); PrivateKey privKey = keyPair.getPrivate(); PublicKey pubKey = keyPair.getPublic(); // Generate the certificate request. X509Name name = new X509Name(dname); DERConstructedSet derSet = new DERConstructedSet(); PKCS10CertificationRequest request = new PKCS10CertificationRequest(sigAlgName, name, pubKey, derSet, privKey); // Save the certificate request to a .pem file. byte[] data = request.getEncoded(); PrintStream ps = new PrintStream(new FileOutputStream(certReqLoc)); // build / delimited name. String certSubject = ""; StringTokenizer tokens = new StringTokenizer(dname, ","); while (tokens.hasMoreTokens()) { certSubject = certSubject + "/" + tokens.nextToken(); } /* ps.print( "\n\n" + "Please mail the following certificate request to " + emailAddressOfCA + "\n" + "\n" + "==================================================================\n" + "\n" + "Certificate Subject:\n" + "\n" + certSubject + "\n" + "\n" + "The above string is known as your user certificate subject, and it \n" + "uniquely identifies this user.\n" + "\n" + "To install this user certificate, please save this e-mail message\n" + "into the following file.\n" + "\n" + "\n" + certLoc + "\n" + "\n" + "\n" + " You need not edit this message in any way. Simply \n" + " save this e-mail message to the file.\n" + "\n" + "\n" + "If you have any questions about the certificate contact\n" + "the Certificate Authority at " + emailAddressOfCA + "\n" + "\n");*/ ps.print(toPEM(data)); ps.close(); // Save private key to a .pem file. OpenSSLKey key = new BouncyCastleOpenSSLKey(privKey); if (password.length() != 0) { key.encrypt(password); } key.writeTo(new File(privKeyLoc).getAbsolutePath()); // set read only permissions Util.setFilePermissions(privKeyLoc, 600); // Create an empty cert file. /* File f = new File(certLoc); f.createNewFile();*/ }