java添加信任_ssl-在Java中使用自定义信任库以及默认的on
您可以使用與上一個(gè)答案中提到的模式類似的模式(針對(duì)另一個(gè)問題)。
本質(zhì)上,掌握默認(rèn)的信任管理器,創(chuàng)建另一個(gè)使用您自己的信任庫的信任管理器。 將它們都包裝在一個(gè)自定義的信任管理器實(shí)現(xiàn)中,該實(shí)現(xiàn)將調(diào)用委派給這兩者(當(dāng)一個(gè)失敗時(shí)回退到另一個(gè))。
TrustManagerFactory tmf = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
// Using null here initialises the TMF with the default trust store.
tmf.init((KeyStore) null);
// Get hold of the default trust manager
X509TrustManager defaultTm = null;
for (TrustManager tm : tmf.getTrustManagers()) {
if (tm instanceof X509TrustManager) {
defaultTm = (X509TrustManager) tm;
break;
}
}
FileInputStream myKeys = new FileInputStream("truststore.jks");
// Do the same with your trust store this time
// Adapt how you load the keystore to your needs
KeyStore myTrustStore = KeyStore.getInstance(KeyStore.getDefaultType());
myTrustStore.load(myKeys, "password".toCharArray());
myKeys.close();
tmf = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(myTrustStore);
// Get hold of the default trust manager
X509TrustManager myTm = null;
for (TrustManager tm : tmf.getTrustManagers()) {
if (tm instanceof X509TrustManager) {
myTm = (X509TrustManager) tm;
break;
}
}
// Wrap it in your own class.
final X509TrustManager finalDefaultTm = defaultTm;
final X509TrustManager finalMyTm = myTm;
X509TrustManager customTm = new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
// If you're planning to use client-cert auth,
// merge results from "defaultTm" and "myTm".
return finalDefaultTm.getAcceptedIssuers();
}
@Override
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
try {
finalMyTm.checkServerTrusted(chain, authType);
} catch (CertificateException e) {
// This will throw another CertificateException if this fails too.
finalDefaultTm.checkServerTrusted(chain, authType);
}
}
@Override
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
// If you're planning to use client-cert auth,
// do the same as checking the server.
finalDefaultTm.checkClientTrusted(chain, authType);
}
};
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[] { customTm }, null);
// You don't have to set this as the default context,
// it depends on the library you're using.
SSLContext.setDefault(sslContext);
您不必將該上下文設(shè)置為默認(rèn)上下文。 如何使用它取決于您使用的客戶端庫(以及從中獲取套接字工廠的位置)。
這就是說,原則上,無論如何,您總是必須根據(jù)需要更新信任庫。 Java 7 JSSE參考指南對(duì)此有一個(gè)“重要說明”,現(xiàn)在在同一指南的版本8中已降級(jí)為“重要說明”:
JDK隨附有限數(shù)量的受信任的根證書?? java-home / lib / security / cacerts文件。 如keytool中所述?? 參考頁,您有責(zé)任進(jìn)行維護(hù)(即添加?? 并刪除)此文件中包含的證書(如果使用?? 文件作為信任庫。
根據(jù)您所使用的服務(wù)器的證書配置?? 聯(lián)系人,則可能需要添加其他根證書。 獲得?? 需要來自適當(dāng)供應(yīng)商的特定根證書。
總結(jié)
以上是生活随笔為你收集整理的java添加信任_ssl-在Java中使用自定义信任库以及默认的on的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 调用接口的方法 java_java调用接
- 下一篇: java 求交集 算法_Java计算交集