You can do this by constructing your own SSLContext
using your own X509KeyManager
and choose the keystore alias
using its chooseClientAlias
method (or chooseServerAlias
, depending on the side).
Something along these lines should work:
// Load the key store: change store type if needed
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream fis = new FileInputStream("/path/to/keystore");
try {
ks.load(fis, keystorePassword);
} finally {
if (fis != null) { fis.close(); }
}
// Get the default Key Manager
KeyManagerFactory kmf = KeyManagerFactory.getInstance(
KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, keyPassword);
final X509KeyManager origKm = (X509KeyManager)kmf.getKeyManagers()[0];
X509KeyManager km = new X509KeyManager() {
public String chooseClientAlias(String[] keyType,
Principal[] issuers, Socket socket) {
// Implement your alias selection, possibly based on the socket
// and the remote IP address, for example.
}
// Delegate the other methods to origKm.
}
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(new KeyManager[] { km }, null, null);
SSLSocketFactory sslSocketFactory = sslContext.getSSLSocketFactory();
(There is a short example here that may help you get started.)
You don't actually have to delegate to the original KeyManager (I just find it more convenient). You could very well implement all its methods to return the keys and certs using the KeyStore you've loaded
Note that this is mostly useful for choosing the client-certificate. Java doesn't support Server Name Indication (SNI) on the server-side (even in Java 7 as far as I know), so you won't be able to know which host name the client is requesting before choosing the alias (from a server point of view).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…