使用证书的 SSL 连接

SSL connection using certificate

我正在尝试编写一个代码,允许我使用带有证书的 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 配置 运行 添加此参数用于调试