How I can tell alias of the wanted key-entry to SSLSocket before connecting?

五迷三道 提交于 2019-11-29 04:07:09

The default KeyManager will send the first certificate it finds that matches the conditions requested by the server, that is, it will send the first one it find for which it can build a certification chain up one of the CA names sent by the server during the request.

If you always want a specific alias to be chosen, you'll need to implement your own X509KeyManager, possibly wrapping the default manager. Something along these lines should work (not tested this actual code, there may be a few 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 your SSLContext:

SSLContext sslContext = sslContext.getInstance("TLS");
sslContext.init(new KeyManager[] { km }, null, null);
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!