Search code examples
androidhostnamesnisslsocketfactory

Suppress sslpeerunverifiedexception while creating socket


I need to set SNI to my socketFactory. So I have been using the class SSLCertificateSocketFactory. While creating an socket, it gives me a sslpeerunverifiedexception, as there is no SAN set, to the server certificate. Can I some how suppress this exception, and ask it to allow creation of socket irrespective of the server certificate?

Following is my code :

            TrustManager tm = new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] chain,
                        String authType) throws CertificateException {
                }

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

                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };

            SSLCertificateSocketFactory ssf = (SSLCertificateSocketFactory) SSLCertificateSocketFactory
                    .getDefault(0);

            ssf.setTrustManagers(new TrustManager[] { tm });

            m_sslsocket = (SSLSocket) ssf.createSocket(m_socket, m_host, m_port, false);

Solution

  • Creating the SSLCertificateSocketFactory with getInsecure worked for me. It returns a new instance of a socket factory with all SSL security checks disabled.

    SSLCertificateSocketFactory ssf = (SSLCertificateSocketFactory) SSLCertificateSocketFactory
                        .getInsecure(0, null);