java - 使用证书的 SSL 连接

标签 java ssl ssl-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 的运行配置添加此参数以进行调试

关于java - 使用证书的 SSL 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38969906/

上一篇:php - 如何使用 wsHTTPBinding 创建 php soap wsdl 客户端?

下一篇:php - Nginx + Xamp + SSL 奇怪的行为

相关文章:

java - CouchDB Java 库由 Maven 下载,但不被 IntelliJ 识别

java - 在java中转置(处理数组)一维数组

java - 如何在 Jboss 5.1.0 中启用 SSL

php - Delphi 应用程序的 SSL 证书 - 是否需要启用安全性?

java - JPA 一对多/多对多示例

java - Android SSL https 发布

java - Apache CXF - 2Way SSL 服务器端 - 无 Spring

python - 如果我忽略 SSL 证书验证,数据仍然是加密的吗?

c++ - 使用 SSL 通配符证书验证主机

java - 为什么 eclipse 或 cmd 控制台会缓存操作系统环境变量?