By default, KeyManager will send the first certificate found to it that matches the conditions requested by the server, that is, it will send the first one found for which it can build a certification chain, using one of the sent CA names by the server during the request.
If you always want the selected alias to be selected, you need to implement your own X509KeyManager , perhaps wrap the default manager, Something should work in this direction (did not check this actual code, there may be several typos):
KeyStore keystore = ... // create and load your keystore. KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(keystore, password.toCharArray()); final X509KeyManager origKm = (X509KeyManager)kmf.getKeyManagers()[0]; X509KeyManager km = new X509KeyManager() { public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) { return "foo"; } public X509Certificate[] getCertificateChain(String alias) { return origKm.getCertificateChain(alias); } // Delegate the rest of the methods from origKm too... }
Then use it for SSLContext :
SSLContext sslContext = sslContext.getInstance("TLS"); sslContext.init(new KeyManager[] { km }, null, null); SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
Bruno
source share