如何使用SSLSocket接受带有Java的自签名证书

时间:2011-05-15 21:23:36

标签: java android

我花了很多时间浏览互联网以找到解决方案.99%的样本都是针对HTTPS的,但我需要让我的代码与SSL服务器一起使用。我无法从中提取许可证,许可证是自签名的。我尝试使用以下代码:

SocketFactory factory = SSLSocketFactory.getDefault(); 
trustAllHosts();

// Get Socket from factory 
SSLSocket socket = (SSLSocket)factory.createSocket("192.168.0.66", 2555); 

BufferedWriter out = new BufferedWriter(new 
        OutputStreamWriter(socket.getOutputStream()));
BufferedReader in = new BufferedReader(
    new InputStreamReader(socket.getInputStream()));
out.write("username");
out.flush();
out.write("password");
out.flush();

我得到:不受信任的服务器证书

我找到了这段代码

    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return new java.security.cert.X509Certificate[] {};
            }

            public void checkClientTrusted(X509Certificate[] chain,
                            String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain,
                            String authType) throws CertificateException {
            }
    } };

但不确定如何应用它。

3 个答案:

答案 0 :(得分:1)

不要申请。这是不安全的。将证书添加到您的信任库。

答案 1 :(得分:1)

感谢您的回复。我没有选择。它是一个硬件设备,我没有证书本身,我可以添加它。

但我使用

修复了它
    SSLContext context = SSLContext.getInstance("TLS");
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[] {};
        }

        public void checkClientTrusted(X509Certificate[] chain,
                        String authType) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain,
                        String authType) throws CertificateException {
        }
} };
    context.init(null, trustAllCerts, null);

答案 2 :(得分:0)

我找到了一个很好的样本here

警告:此代码不安全

我们正在做的是忽略证书

{ "_id" : ObjectId("56db9f73df8599420b7d258a"), "email" : "test.user1@email.com", "car" : null, "__v" : 0 }
{ "_id" : ObjectId("56db9f73df8599420b7d258b"), "email" : "test.user1@email.com", "car" : { "carType" : 23 }, "__v" : 0 }

记得使用这一行

SSLContext context = SSLContext.getInstance("TLS");
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[] {};
    }

    public void checkClientTrusted(X509Certificate[] chain,
                    String authType) throws CertificateException {
    }

    public void checkServerTrusted(X509Certificate[] chain,
                    String authType) throws CertificateException {
    }
} };
context.init(null, trustAllCerts, null);

SocketFactory factory = context.getSocketFactory();
...

而不是

SocketFactory factory = context.getSocketFactory();