gpt4 book ai didi

Java keystore - 以编程方式从 keystore 文件中选择要使用的证书

转载 作者:太空宇宙 更新时间:2023-11-03 13:23:12 27 4
gpt4 key购买 nike

我有一个包含多个客户端证书的 Java keystore 文件。我希望在我的 Java 应用程序中仅选择这些证书之一来连接到服务。有没有简单的方法可以做到这一点?到目前为止,我找到解决方案的唯一方法是使用原始 keystore 文件中的客户端证书详细信息(通过其别名找到)在程序中创建一个新的 keystore 。我虽然可能有一种简单的方法只是说“使用带有此别名的 keystore.jks 文件中的证书”,而不必仅为要使用的证书创建一个新的 keystore 。代码如下:

        // Set up Client Cert settings
KeyStore clientCertStore = KeyStore.getInstance("JKS");
clientCertStore.load(new FileInputStream(clientKeystoreLocation), clientKeystorePassword);

// Create temporary one keystore, then extract the client cert using it's alias from keystore.jks, then create
// a new keystore with this cert, that the process will use to connect with.
KeyStore tempKstore = KeyStore.getInstance("JKS");
tempKstore.load(null);
tempKstore.setKeyEntry(certificateAlias, clientCertStore.getKey(certificateAlias, bwConfig.clientKeystorePassword),
clientKeystorePassword, clientCertStore.getCertificateChain(certificateAlias));
clientCertStore = tempKstore;

KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(clientCertStore, clientKeystorePassword);

// Set up Truststore settings
File truststoreFile = new File(TrustStoreLocation);
KeyStore trustStore = KeyStore.getInstance("JKS");
trustStore.load(new FileInputStream(truststoreFile), TrustStorePassword);
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(trustStore);

// Set to TLS 1.2 encryption
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

SSLSocketFactory ssf = sslContext.getSocketFactory();
ssf.createSocket(serviceURL.getHost(), servicePort);

bp.getRequestContext().put("com.sun.xml.internal.ws.transport.https.client.SSLSocketFactory", ssf);

最佳答案

您的问题类似于How I can tell alias of the wanted key-entry to SSLSocket before connecting?

默认的KeyManager会选择握手中的第一个证书(根据服务器发送的CA列表),您可以构建自己的X509KeyManager来指定要使用的别名包装默认值。

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 ...
}

SSLContext 中设置新的 keyManager

 sslContext.init(new KeyManager[] { km }, trustManagerFactory.getTrustManagers(), null);

关于Java keystore - 以编程方式从 keystore 文件中选择要使用的证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42442721/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com