有很多关于如何使用Apache HTTPClient忽略SSL证书的例子;我根据this SO答案创建了一个客户端。到现在为止还挺好。问题是,当证书无效时,客户盲目地接受它,就像我告诉它一样。但我不想悄悄地接受它;我想记录某种警告,让我知道接受了无效的证书。
有没有办法做到这一点?
P.S。:这是内部工具,而不是产品代码。我理解并接受忽视证书的风险,所以,请不要开始“比你更圣洁”的演讲。
答案 0 :(得分:0)
只需简单地解决传递给X509TrustManager
方法的SSLContext#init
个实例
static class TrustManagerDelegate implements X509TrustManager {
private final X509TrustManager trustManager;
TrustManagerDelegate(final X509TrustManager trustManager) {
super();
this.trustManager = trustManager;
}
@Override
public void checkClientTrusted(
final X509Certificate[] chain, final String authType) throws CertificateException {
trustManager.checkClientTrusted(chain, authType);
}
@Override
public void checkServerTrusted(
final X509Certificate[] chain, final String authType) {
try {
trustManager.checkServerTrusted(chain, authType);
} catch (CertificateException ex) {
// Implement proper logging;
System.out.println(chain[0]);
ex.printStackTrace(System.out);
}
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return trustManager.getAcceptedIssuers();
}
}
...
TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmfactory.init((KeyStore) null);
final TrustManager[] tms = tmfactory.getTrustManagers();
if (tms != null) {
for (int i = 0; i < tms.length; i++) {
final TrustManager tm = tms[i];
if (tm instanceof X509TrustManager) {
tms[i] = new TrustManagerDelegate((X509TrustManager) tm);
}
}
}
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tms, null);
CloseableHttpClient client = HttpClientBuilder.create()
.setSSLContext(sslContext)
.build();