【问题标题】:JavaFX WebView not working using a untrusted SSL certificateJavaFX WebView 无法使用不受信任的 SSL 证书工作
【发布时间】:2014-03-24 09:42:23
【问题描述】:

我正在使用 JavaFX 开发一个简单的嵌入式浏览器:

final WebView browser = new WebView();
final WebEngine webEngine = browser.getEngine();

当我使用webEngine 加载任何http 网站时,它工作正常:

webEngine.load("http://google.es");

尽管如此,如果我尝试使用不受信任的证书(我自己的 ssl 证书)加载网站,webEngine 不起作用,并且我在浏览器中看到白屏。

有没有办法(自动)信任我的 ssl 证书?

【问题讨论】:

    标签: java ssl https javafx certificate


    【解决方案1】:

    最后,我解决了我的问题。您应该在加载网站之前添加此代码:

    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { 
        new X509TrustManager() {     
            public java.security.cert.X509Certificate[] getAcceptedIssuers() { 
                return null;
            } 
            public void checkClientTrusted( 
                java.security.cert.X509Certificate[] certs, String authType) {
                } 
            public void checkServerTrusted( 
                java.security.cert.X509Certificate[] certs, String authType) {
            }
        } 
    }; 
    
    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL"); 
        sc.init(null, trustAllCerts, new java.security.SecureRandom()); 
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (GeneralSecurityException e) {
    } 
    // Now you can access an https URL without having the certificate in the truststore
    try { 
        URL url = new URL("https://hostname/index.html"); 
    } catch (MalformedURLException e) {
    } 
    //now you can load the content:
    
    webEngine.load("https://example.com");
    

    注意:此代码片段只是禁用证书验证,而不是信任它。

    【讨论】:

    • 有很多更好(和安全)的方法可以做到这一点,请参阅this answer:创建一个新的密钥库(可能基于默认的cacerts 文件的副本),导入您的自签名证书,然后使用它来初始化您的信任管理器。
    猜你喜欢
    • 1970-01-01
    • 2016-01-15
    • 1970-01-01
    • 2015-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-14
    • 1970-01-01
    相关资源
    最近更新 更多