Java Keystore - programatically select the certificate to use from keystore file

前端 未结 1 1864
失恋的感觉
失恋的感觉 2021-02-06 19:14

I have a java keystore file which contains multiple client certificates. I wish to select just one of these certificates in my Java application to connect to a service. Is the

相关标签:
1条回答
  • 2021-02-06 19:41

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

    The default KeyManager will select the first certificate in handshake (according to CA list sent by server), You can build your own X509KeyManager to specify the alias to be used wrapping the default.

    final X509KeyManager origKm = (X509KeyManager)keyManagerFactory.getKeyManagers()[0];
    X509KeyManager km = new X509KeyManager() {
       public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) {
           return "alias";
       }
    
       public X509Certificate[] getCertificateChain(String alias) {
           return origKm.getCertificateChain(alias);
       }
    
    // override the rest of the methods delegating to origKm ...
    }
    

    Set the new keyManager in SSLContext

     sslContext.init(new KeyManager[] { km }, trustManagerFactory.getTrustManagers(), null);
    
    0 讨论(0)
提交回复
热议问题