OkHttp javax.net.ssl.SSLPeerUnverifiedException: Hostname domain.com not verified

后端 未结 5 1306
小鲜肉
小鲜肉 2020-12-04 18:45

I\'ve been trying for days to get this working. I\'m trying to connect to my server over https with a self signed certificate. I don\'t think there is any p

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-04 19:08

    I finally got this working with a mix of multiple answers.

    First, the certificates was made wrongly, not sure how. But by creating them using the script in this answer made them work. What was needed was a server certificate and a key. Then the client needed another certificate.

    To use the certificate in android I converted the .pem file to a .crt file like this:

    openssl x509 -outform der -in client.pem  -out client.crt
    

    In android I added the certificate to my OkHttp client like the following:

    public ApiService() {
        mClient = new OkHttpClient();
        mClient.setConnectTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS);
        mClient.setReadTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS);
        mClient.setCache(getCache());
        mClient.setSslSocketFactory(getSSL());
    }
    
    protected SSLSocketFactory getSSL() {
        try {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            InputStream cert = getAppContext().getResources().openRawResource(R.raw.client);
            Certificate ca = cf.generateCertificate(cert);
            cert.close();
    
            // creating a KeyStore containing our trusted CAs
            String keyStoreType = KeyStore.getDefaultType();
            KeyStore keyStore = KeyStore.getInstance(keyStoreType);
            keyStore.load(null, null);
            keyStore.setCertificateEntry("ca", ca);
    
            return new AdditionalKeyStore(keyStore);
        } catch(Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    

    The last part with new AdditionalKeyStore() is taken from this very well written answer. Which adds a fallback keystore.

    I hope this might help anyone else! This is the simplest way to get HTTPS working with a self-signed certificate that I have found. Other ways include having a BouncyCastle keystore which seems excessive to me.

提交回复
热议问题