How do I programmatically create a private key and use it in a SSL socket?
I put a commented exception below where I’m trying to add the key to the keystore but I do not have a certificate chain.
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1024, new SecureRandom());
KeyPair keypair = keyGen.generateKeyPair();
System.setProperty("javax.net.ssl.keyStore", System.getProperty("user.home")
+ File.separator +
+ "/keystore.jks");
System.setProperty("javax.net.ssl.keyStorePassword", "xyz");
KeyManagerFactory keyManagerFactory = KeyManagerFactory
.getInstance("SunX509");
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(null, "xyz".toCharArray());
//setKeyEntry parameter 3 can not be null:
//IllegalArgumentException: Private key must be accompanied by certificate chain
keyStore.setKeyEntry("alias", keypair.getPrivate(),
"xyz".toCharArray(), null);
keyManagerFactory.init(keyStore, "xyz".toCharArray());
// keyStore.load
SSLContext context = SSLContext.getInstance("TLS");// "SSLv3"
context.init(keyManagerFactory.getKeyManagers(), null,
new SecureRandom());
ServerSocketFactory socketFactory = context.getServerSocketFactory();
ServerSocket ssocket = socketFactory.createServerSocket(1443);
Socket socket = ssocket.accept();
There is little point creating only a private key, or even just a private/public key pair. What you need to set up on your server is a certificate associated with this private key.
X.509 certificates are rather complex structures, based on ASN.1 syntax. I’d strongly suggest you use BouncyCastle (more or less as described in the blog article you link to). Doing it all by hand is no simple task. (If you’re not convinced, look at the source code of the BouncyCastle classes.)
In addition, there’s little point in creating this certificate (and its associated private key) dynamically. The point of the certificate is to allow the client to verify the identity of the server it’s talking to. The client does this by checking the server cert against a list of trusted certificates it has (either using a PKI or by individual comparison against specific server certificates that have been manually configured).
If you generate a self-signed certificate dynamically, there is no way for the client to compare it against something it would have known in advance. It could potentially be useful if your server is also a CA (for applications similar to MITM-proxy servers).