gpt4 book ai didi

java - 使用 Java 的 SunMSCAPI/Windows-MY 访问用于 TLS/SSL 连接的智能卡证书与客户端身份验证

转载 作者:可可西里 更新时间:2023-11-01 10:31:58 26 4
gpt4 key购买 nike

我有一个 Java 应用程序,它使用智能卡中的证书进行 TLS/SSL 客户端身份验证。智能卡有 2 个证书,一个用于签名,另一个用于身份验证。我就是这样做的:

    // loading windows-my store
KeyStore windowsMyKeyStore = KeyStore.getInstance("Windows-MY", "SunMSCAPI");
windowsMyKeyStore.load(null, null);
// loading keymanager
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(windowsMyKeyStore, null);
// building truststore
TrustManager[] trustAllManager = new TrustManager[]{new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}};
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagerFactory.getKeyManagers(), trustAllManager, new SecureRandom());
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
new String[]{"TLSv1.2", "TLSv1.1"},
null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
HttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(sslConnectionSocketFactory)
.build();
HttpGet get = new HttpGet(...);

问题的发生是因为 Java 选择了与来自服务器的 CertificateRequest 匹配的第一个 证书(错误的证书),正如在 -Djavax.net.debug=all 时的摘录中所见:

*** ServerHelloDone
[read] MD5 and SHA1 hashes: len = 4
0000: 0E 00 00 00 ....
matching alias: <<alias for SIGNING certificate>>
matching alias: <<alias for AUTHENTICATION certificate>>
*** Certificate chain
chain [0] = [
<< SIGNING certificate >>
]

是否可以配置 Java 以使其使用正确的证书?

最佳答案

同样的问题,我是这样解决的:

KeyStore windowsMyKeyStore = KeyStore.getInstance("Windows-MY", "SunMSCAPI");
windowsMyKeyStore.load(null, null);

SSLContext sslContext = SSLContexts.custom().loadKeyMaterial(windowsMyKeyStore, null, new PrivateKeyStrategy() {
@Override
public String chooseAlias(Map<String, PrivateKeyDetails> aliases, Socket socket) {
for (String alias : aliases.keySet()) {
PrivateKeyDetails privateKeyDetails = aliases.get(alias);
for (X509Certificate certificate : privateKeyDetails.getCertChain()) {
try {
certificate.checkValidity();
List<String> extKeyUsage = certificate.getExtendedKeyUsage();
if (extKeyUsage != null && extKeyUsage.contains("1.3.6.1.5.5.7.3.2"))
return alias;
} catch (CertificateExpiredException | CertificateNotYetValidException | CertificateParsingException e) {
continue;
}
}
}

return null;
}
}).build();

关于java - 使用 Java 的 SunMSCAPI/Windows-MY 访问用于 TLS/SSL 连接的智能卡证书与客户端身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52194306/

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