在我的Android应用程序(这是一个测试应用程序)中,我执行以下disableSslValidation方法来禁用SSL证书验证。现在,无需重新启动该过程,我想启用SSL证书验证。我该怎么做?

编辑:我完全了解禁用SSL验证所涉及的风险,并有意识地接受上述风险。

private void disableSslValidation() throws KeyManagementException, NoSuchAlgorithmException {
    // 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(X509Certificate[] certs, String authType) {}

        public void checkServerTrusted(X509Certificate[] certs, String authType) {}
    } };

    // Install the all-trusting trust manager
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}

最佳答案

由于这是测试代码,因此建议您将其丢弃。您不希望不安全的代码泄漏到生产中。您甚至都不希望它出现在应用程序中。

10-04 10:10