<分区>
<分区>
我正在尝试编写一个代码,允许我使用带有证书的 SSL 连接来连接到服务器。
我有证书,它是一个 .crt
文件。
我已经组装了一个代码,但它不起作用:
public class SSLClient {
public static void main(String[] args) throws Exception{
String strServerName = "Some Server"; // SSL Server Name
int intSSLport = 443; // Port where the SSL Server is listening
PrintWriter out = null;
BufferedReader in = null;
{
// Registering the JSSE provider
Security.addProvider(new Provider());
}
try {
// Creating Client Sockets
SSLSocketFactory sslfac = (SSLSocketFactory)SSLSocketFactory.getDefault();
SSLSocket socket = (SSLSocket)sslfac.createSocket(strServerName,intSSLport);
System.setProperty("javax.net.ssl.keyStore", "D:/projects/TemporaryTesting/certificate.crt");
// Initializing the streams for Communication with the Server
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput = "Hello Testing ";
out.println(userInput);
System.out.println("echo: " + in.readLine());
// Closing the Streams and the Socket
out.close();
in.close();
stdIn.close();
socket.close();
}
catch(Exception exp)
{
System.out.println(" Exception occurred .... " +exp);
exp.printStackTrace();
}
}}
这是我遇到的错误:
javax.net.ssl.SSLException: Connection has been shutdown: 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 targetjavax.net.ssl.SSLException: Connection has been shutdown: 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
我做错了什么? 在我使用它之前,我是否必须以某种方式用 java 注册证书? 我如何解决它? 这是我第一次接触 SSL 连接,因此我们将不胜感激。
最佳答案
我记得做过几件事,比如在 eclipse 中安装 keytool,将证书导入 eclipse
同样在cmd中手动导入到lib/security下JDK文件夹中的cacerts
文件
http://magicmonster.com/kb/prg/java/ssl/pkix_path_building_failed.html
最后在 eclipse 中为我的 maven 项目 -Djavax.net.debug=all
的运行配置添加此参数以进行调试
关于java - 使用证书的 SSL 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38969906/