所以,我试图通过在Java程序中使用客户端证书来测试与我公司的Web服务器的连接(使用双向SSL)。我尝试在curl调用中使用相同的证书(分离的证书和密钥)并设法获得所需的响应。但是当我尝试在我的Java程序中使用它(结合到pkcs12格式)时,它给出了400响应,说没有发送所需的SSL证书。为什么会这样?
public static void main(String[] args) {
System.out.println("Taufiq's mutual SSL-authentication test");
org.apache.log4j.BasicConfigurator.configure();
Logger.getRootLogger().setLevel(Level.INFO);
try {
final String CERT_ALIAS = "something", CERT_PASSWORD = "something";
KeyStore identityKeyStore = KeyStore.getInstance("pkcs12");
FileInputStream identityKeyStoreFile = new FileInputStream(new File("src/Cert.p12"));
identityKeyStore.load(identityKeyStoreFile, CERT_PASSWORD.toCharArray());
KeyStore trustKeyStore = KeyStore.getInstance("jks");
FileInputStream trustKeyStoreFile = new FileInputStream(new File("src/truststore.jks"));
trustKeyStore.load(trustKeyStoreFile, CERT_PASSWORD.toCharArray());
SSLContext sslContext = SSLContexts.custom()
// load identity keystore
.loadKeyMaterial(identityKeyStore, CERT_PASSWORD.toCharArray(), new PrivateKeyStrategy() {
@Override
public String chooseAlias(Map<String, PrivateKeyDetails> aliases, Socket socket) {
return CERT_ALIAS;
}
})
// load trust keystore
.loadTrustMaterial(trustKeyStore, null)
.build();
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
new String[]{"TLSv1.2", "TLSv1.1"},
null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
CloseableHttpClient client = HttpClients.custom()
.setSSLSocketFactory(sslConnectionSocketFactory)
.build();
// Call a SSL-endpoint
callEndPoint (client);
} catch (Exception ex) {
System.out.println("Boom, we failed: " + ex);
ex.printStackTrace();
}
}
private static void callEndPoint(CloseableHttpClient aHTTPClient) {
try {
String ServerUrl = "My Company URL";
System.out.println("Calling URL: " + ServerUrl);
HttpPost post = new HttpPost(ServerUrl);
post.setHeader("Content-type", "application/json");
System.out.println("**POST** request Url: " + post.getURI());
HttpResponse response = aHTTPClient.execute(post);
int responseCode = response.getStatusLine().getStatusCode();
System.out.println("Response Code: " + responseCode);
System.out.println("Content:-\n");
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
} catch (Exception ex) {
System.out.println("Boom, we failed: " + ex);
ex.printStackTrace();
}
}
示例卷曲调用:curl -v --key key.pem --pass ****** --cert cert.pem MyCompanyURL
我猜你知道ssl握手是如何工作的。如果没有,请认识一下。然后使用wireshark查看ssl握手。你会得到比一些该死的http库解释更好的ssl警报细节。如果有的话,这是一个误导性的错误。
可以肯定的是,您的服务器必须信任您的客户端证书,因此我假设您首先正确设置了某些内容;你说你已经尝试过卷曲,但你没有说它是否有效。
最后,我不认识这些SSL类,所以你要导入的东西不是jdk的jsse类;你可能是这种图书馆的受害者。
事实证明,当我使用核心jdk jsse类时,程序运行正常。我使用上面的程序,因为我正在复制互联网上的一个例子。