![](/img/trans.png)
[英]javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No X509TrustManager implementation available
[英]Restore SSL X509TrustManager in Java
我有以下代碼,這些代碼有條件地(基於boolean
)禁用SSL證書檢查。
但是,如果我將boolean
設置為false
並重新運行代碼,則SSL檢查似乎仍處於禁用狀態(應重新啟用)。
那么,與此相反的邏輯是什么,以便恢復檢查?
if (bIgnoreSSL) {
TrustManager[] trustAllCertificates = new TrustManager[] {
new X509TrustManager()
{
@Override
public X509Certificate[] getAcceptedIssuers() { return null; // Not relevant.}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) { // Do nothing. Just allow them all. }
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType){ // Do nothing. Just allow them all.}
}
};
HostnameVerifier trustAllHostnames = new HostnameVerifier()
{
@Override
public boolean verify(String hostname, SSLSession session) { return true; // Just allow them all. }
};
try
{
System.setProperty("jsse.enableSNIExtension", "false");
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCertificates, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(trustAllHostnames);
}
catch (GeneralSecurityException e)
{
throw new ExceptionInInitializerError(e);
}
}
else {
// Code to restore here (Opposite of above?)
}
一種選擇是先將默認值保存在變量中,以便以后可以將其還原:
// save defaults (do this before setting another defaults)
HostnameVerifier defaultVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
SSLSocketFactory defaultFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
if (bIgnoreSSL) {
...
} else {
// restore defaults
HttpsURLConnection.setDefaultHostnameVerifier(defaultVerifier);
HttpsURLConnection.setDefaultSSLSocketFactory(defaultFactory);
}
另一種替代方法(更好的方法是IMO)是不為所有連接設置默認值,而是為每個單獨的連接設置:
HttpsURLConnection conn = // create connection
if (bIgnoreSSL) {
// set custom verifier and factory only for this connection
conn.setHostnameVerifier(trustAllHostnames);
conn.setSSLSocketFactory(sc.getSocketFactory());
}
// no need to restore (else), as I didn't change the defaults
這僅更改指定連接器的驗證程序和工廠,而不會影響默認設置(因此無需還原)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.