我使用 HttpsURLConnection 向服务器发送请求。 第一次,我使用一种简单的方法在 Java https 连接中通过证书验证并且它有效。 (根据网站: http://www.nakov.com/blog/2009/07/16/disable-certificate-validation-in-java-ssl-connections/ )
但是现在,我得到了一个 .pem
文件,我需要将它导入到我的 JVM 中。
我试图通过 keytool -import -file E:\server.pem -alias SERVER -keystore "C:\Program Files\Java\jre7\lib 将
,但出现错误 .pem
文件导入我的 JVM\security\cacerts"java.lang.Exception: not X.509
。
因此,我使用openssl将.pem
转为.der
。然后我通过 keytool -import -file E:\server.der -alias SERVER -keystore "C:\Program Files\Java\jre7\lib\security 将
..der
导入到我的 JVM\cacerts"
但是当我在没有通过证书验证的情况下执行代码时,它有关于 "javax.net.ssl.SSLHandshakeException: ...: PKIX path building failed: java.security.cert.CertPathBuilderException:"的错误
我该如何解决?是不是自己把.pem
转成.der
导致的错误?服务器是否也必须使用 .der
?
谢谢!
通过证书验证
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(new KeyManager[0], new TrustManager[] {new DefaultTrustManager()}, new SecureRandom());
SSLContext.setDefault(ctx);
// HttpsURLConnection
URL url = new URL(newUrl);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
});
connection.connect();
BufferedReader reader = null;
String json;
// read the output from the server
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
json = reader.readLine();
connection.disconnect();
导入证书
我可以在导入证书后删除一些代码,例如 SSLContext...
吗?
// HttpsURLConnection
URL url = new URL(newUrl);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
BufferedReader reader = null;
String json;
// read the output from the server
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
json = reader.readLine();
connection.disconnect();
部分server.pem
-----BEGIN PRIVATE KEY-----
MIICdwIBADANBgkqhk
....
....
4QOYP5BR7kze/gY=
-----END PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
MIICSjCCAbOgAwIBAgIJAL9cT+
....
....
bfnoA/x+53HmG0w6fu
x8HXcTCrgsgnYwoMl9A=
-----END CERTIFICATE-----
最佳答案
如果您的服务器有一个自签名证书并且您想忽略对证书验证的检查,您可以this code (ignoring-self-signed-certificates-in-java) :).非常适合我。
关于java - 如何在HttpsURLConnection中正确导入认证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20344910/