Java:覆盖功能以禁用 SSL 证书检查 [英] Java: Overriding function to disable SSL certificate check

查看:34
本文介绍了Java:覆盖功能以禁用 SSL 证书检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Web 服务基于 SSL,它具有自签名证书,托管在远程系统中.我已经创建了一个访问该 Web 服务的客户端.这是通过将证书添加到密钥存储区来完成的.

The web service is rest over SSL and it has self signed certificate, hosted in remote system.I have already created a client accessing that web service. This is done by adding the certificate to the key store programatically.

现在我听说,无需将证书添加到密钥库即可访问自签名 Web 服务.相反,我们可以通过覆盖某些方法来禁用证书检查.这是真的?有哪些方法?请帮忙.

Now I heard that, it is not necessary to add certificate to key store for accesing a self signed web service. Instead we can disable the certificate check by overriding some methods. Is this true? Which are those methods? Please help.

推荐答案

这应该足够了.我在针对我们没有正确签名证书的测试和登台服务器测试代码时使用它.但是,您真的应该认真考虑在您的生产服务器上获取有效的 SSL 证书.没有人愿意被窃听并侵犯他们的隐私.

This should be sufficient. I use this when testing code against testing and staging servers where we don't have properly signed certificates. However, you should really really strongly consider getting a valid SSL certificate on your production server. Nobody wants to be wiretapped and have their privacy violated.

SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, new TrustManager[] { new TrustAllX509TrustManager() }, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier(){
    public boolean verify(String string,SSLSession ssls) {
        return true;
    }
});

还有这个.

import javax.net.ssl.X509TrustManager;
import java.security.cert.X509Certificate;

/**
 * DO NOT USE IN PRODUCTION!!!!
 * 
 * This class will simply trust everything that comes along.
 * 
 * @author frank
 *
 */
public class TrustAllX509TrustManager implements X509TrustManager {
    public X509Certificate[] getAcceptedIssuers() {
        return new X509Certificate[0];
    }

    public void checkClientTrusted(java.security.cert.X509Certificate[] certs,
            String authType) {
    }

    public void checkServerTrusted(java.security.cert.X509Certificate[] certs,
            String authType) {
    }

}

祝你好运!

===更新===

我只想指出,有一个名为 Let's Encrypt 的服务可以自动生成和设置 SSL/几乎所有人都认可的 TLS 证书,而且完全免费!

I just wanted to point out that there's a service called Let's Encrypt which automates the process of generating and setting up SSL/TLS certificates recognised by virtually everybody, and it's absolutely free!

这篇关于Java:覆盖功能以禁用 SSL 证书检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆