我正在尝试编写一个代码,允许我使用带证书的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连接,所以任何帮助都会受到赞赏。
答案 0 :(得分:0)
我记得做过几件事,比如在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
的运行配置中添加此参数以进行调试