如何在特定連接上使用不同的證書?我在我們的大型Java應(yīng)用程序中添加了一個模塊,它必須與另一家公司的SSL安全網(wǎng)站進(jìn)行交互。問題是網(wǎng)站使用自簽名證書。我有一個證書副本來驗(yàn)證我沒有遇到中間人攻擊,我需要將這個證書合并到我們的代碼中,這樣到服務(wù)器的連接就會成功。以下是基本代碼:void sendRequest(String dataPacket) {
String urlStr = "https://host.example.com/";
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setMethod("POST");
conn.setRequestProperty("Content-Length", data.length());
conn.setDoOutput(true);
OutputStreamWriter o = new OutputStreamWriter(conn.getOutputStream());
o.write(data);
o.flush();}如果沒有對自簽名證書進(jìn)行任何額外的處理,它就會死在con.getOutputStream()上,但有以下例外:Exception in thread "main" javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target....
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException:
unable to find valid certification path to requested target....Caused by: sun.security.provider.certpath.SunCertPathBuilderException:
unable to find valid certification path to requested target理想情況下,我的代碼需要教Java接受這個自簽名證書,這是應(yīng)用程序中的一個地方,而不是其他地方。我知道我可以將證書導(dǎo)入到JRE的證書頒發(fā)機(jī)構(gòu)存儲中,這將允許Java接受它。如果我能幫忙的話,這不是我想要采取的一種方法;在我們所有客戶的機(jī)器上使用他們可能不使用的模塊,這似乎很有侵略性;它會影響使用相同JRE的所有其他Java應(yīng)用程序,即使其他Java應(yīng)用程序訪問這個站點(diǎn)的幾率為零,我也不喜歡這樣做。這也不是一個簡單的操作:在UNIX上,我必須獲得訪問權(quán)才能以這種方式修改JRE。我還看到我可以創(chuàng)建一個TrustManager實(shí)例來執(zhí)行一些自定義檢查??雌饋?,我甚至可以創(chuàng)建一個TrustManager,它在所有情況下都委托給真正的TrustManager,但這個證書除外。但看起來TrustManager是在全球范圍內(nèi)安裝的,我想這會影響到我們應(yīng)用程序中的所有其他連接,這對我來說也不太合適。設(shè)置Java應(yīng)用程序以接受自簽名證書的首選、標(biāo)準(zhǔn)或最佳方法是什么?我能完成我在上面想到的所有目標(biāo)嗎?還是我要妥協(xié)?是否有涉及文件、目錄和配置設(shè)置以及小到無代碼的選項(xiàng)?
3 回答

揚(yáng)帆大魚
TA貢獻(xiàn)1799條經(jīng)驗(yàn) 獲得超9個贊
SSLSocket
HttpsURLConnection
...HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();conn.setSSLSocketFactory(sslFactory);conn.setMethod("POST");...
SSLSocketFactory
/* Load the keyStore that includes self-signed cert as a "trusted" entry. */KeyStore keyStore = ... TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());tmf.init(keyStore);SSLContext ctx = SSLContext. getInstance("TLS");ctx.init(null, tmf.getTrustManagers(), null);sslFactory = ctx.getSocketFactory();
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());keyStore.load(trustStore, trustStorePassword);trustStore.close();
CertificateFactory
keytool
keytool -import -file selfsigned.pem -alias server -keystore server.jks
添加回答
舉報(bào)
0/150
提交
取消