【发布时间】:2019-07-22 10:32:01
【问题描述】:
因此,我正在尝试通过在 Java 程序中使用客户端证书来测试与我公司 Web 服务器的连接(使用 2 路 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 调用示例: curl -v --key key.pem --pass ****** --cert cert.pem MyCompanyURL
【问题讨论】:
-
看看你在
curl中使用的确切命令会很有用? -
我会说,在客户端,您需要服务器证书,而不是客户端证书。
-
@DmytroChasovskyi 我已经编辑了我的问题以包含 curl 调用
-
@VictorCalatramas 据我了解,服务器证书进入信任库,客户端证书将在进行 2 路 ssl 调用时发送。如果我错了,请纠正我
-
一切都取决于服务器的实现,可以确定的是客户端和服务器需要彼此的证书(.pem)
标签: java ssl ssl-certificate client-certificates