accepting HTTPS connections with self-signed certificates

前端 未结 13 2234
小蘑菇
小蘑菇 2020-11-22 04:20

I\'m trying to make HTTPS connections, using HttpClient lib, but the problem is that, since the certificate isn\'t signed by a recognized Certificate Authority

13条回答
  •  没有蜡笔的小新
    2020-11-22 05:01

    The top answer didn´t work for me. After some investigation I found the required information on "Android Developer": https://developer.android.com/training/articles/security-ssl.html#SelfSigned

    Creating an empty implementation of X509TrustManager did the trick:

    private static class MyTrustManager implements X509TrustManager
    {
    
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType)
             throws CertificateException
        {
        }
    
        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType)
            throws CertificateException
        {
        }
    
        @Override
        public X509Certificate[] getAcceptedIssuers()
        {
            return null;
        }
    
    }
    
    ...
    
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    try
    {
        // Create an SSLContext that uses our TrustManager
        SSLContext context = SSLContext.getInstance("TLS");
        TrustManager[] tmlist = {new MyTrustManager()};
        context.init(null, tmlist, null);
        conn.setSSLSocketFactory(context.getSocketFactory());
    }
    catch (NoSuchAlgorithmException e)
    {
        throw new IOException(e);
    } catch (KeyManagementException e)
    {
        throw new IOException(e);
    }
    conn.setRequestMethod("GET");
    int rcode = conn.getResponseCode();
    

    Please be aware that this empty implementation of TustManager is just an example and using it in a productive environment would cause a severe security threat!

提交回复
热议问题