Android okhttp3.0 configure https self-signed certificate and trust all certificates

tags: Https  Okhttp  Retrofit  android

1.Https related knowledge

1.1 The difference between http and https

The data transmitted by the HTTP protocol is unencrypted, that is, plaintext. Therefore, it is very insecure to use the HTTP protocol to transmit private information. In order to ensure that these private data can be encrypted and transmitted, Netscape has designed the SSL (Secure Sockets Layer) protocol. The HTTPS was born by encrypting the data transmitted by the HTTP protocol. To put it simply, the HTTPS protocol is a network protocol built by the SSL+HTTP protocol for encrypted transmission and identity authentication, which is more secure than the http protocol.

The differences between HTTPS and HTTP are as follows:

  • The https protocol needs to apply for a certificate at ca, and generally there are fewer free certificates, so a certain fee is required.

  • Http is a hypertext transfer protocol, the information is transmitted in clear text, and https is a secure ssl encrypted transport protocol.

  • Http and https use a completely different connection method, and the ports used are different. The former is 80 and the latter is 443.

  • The connection of http is very simple and stateless; HTTPS protocol is a network protocol built by SSL+HTTP protocol for encrypted transmission and identity authentication, which is more secure than http protocol.

1.2 Advantages of Https

  • Authenticate users and servers to ensure data is sent to the correct client and server; (verification certificate)

  • Encrypt data to prevent data from being stolen in the middle; (encryption)

  • Maintain data integrity and ensure that data is not altered during transmission. (abstract algorithm)

2. Use self-signed certificate in Okhttp

The website that generally supports https is a certificate issued by a CA (Certificate Authority) organization. However, the certificate issued by the organization generally requires a fee and has a limitation on the use time. Otherwise the link is untrusted by default and cannot be accessed directly via okHttp.

However, we can use the self-signed method to generate a certificate of its own through the keytool.exe that comes with the JDK, and then use the certificate content. Although the prompt "Unsafe" will also appear, we can access the link via okhttp.

2.1 Using a self-signed certificate

Place the certificate file in the assets directory (it can also be placed in other directories, as long as the file can be read correctly), sslSocketFactory() adds the certificate information when creating the OkhttpClient object.

private SSLContext getSLLContext() {
        SSLContext sslContext = null;
        try {
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            InputStream certificate = mContext.getAssets().open("gdroot-g2.crt");
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null);
            String certificateAlias = Integer.toString(0);
            keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate));
            sslContext = SSLContext.getInstance("TLS");
            final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(keyStore);
            sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        return sslContext;
    }

Through the above code, we can see that the certificate information is read by InputStream. Therefore, in order to avoid packaging the certificate file into the APK, we can directly put the contents of the certificate file in String and convert the string into a stream.

When using okhttp, set it to sslSocketFactory.

OkHttpClient httpClient = new OkHttpClient().newBuilder()
                .sslSocketFactory(getSLLContext().getSocketFactory())
                .build();

2.2 Trust all certificates

By adding a certificate, you can implement the function of the client accessing the Https server. However, if the server replaces the certificate content, the client needs to replace the https certificate accordingly. Otherwise, the data cannot be obtained through normal interaction. We can customize the X509TrustManager. Formal implementation to circumvent all certificate detection and achieve the purpose of trusting all certificates.

 private OkHttpClient getHttpsClient() {
        OkHttpClient.Builder okhttpClient = new OkHttpClient().newBuilder();
        //trust all server addresses
        okhttpClient.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                                 / / set to true
                return true;
            }
        });
                 / / Create a manager
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(
                    java.security.cert.X509Certificate[] x509Certificates,
                    String s) throws java.security.cert.CertificateException {
            }

            @Override
            public void checkServerTrusted(
                    java.security.cert.X509Certificate[] x509Certificates,
                    String s) throws java.security.cert.CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[] {};
            }
        } };
        try {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

                         / / Set sslSocketFactory for OkHttpClient
            okhttpClient.sslSocketFactory(sslContext.getSocketFactory());

        } catch (Exception e) {
            e.printStackTrace();
        }

        return okhttpClient.build();
    }

Create an X509TrustManager object and implement its methods. Since X509TrustManager is a universal certificate format, you only need to get the format. Finally init the security protocol, put it into the sslSocketFactory of okhttp.
Since Retrofit is only a wrapper around the Okhttp network interface, this method is equally applicable to Retrofit.

Intelligent Recommendation

Android implements https network communication by adding specified trust certificate / trusting all certificates

When the Android client accesses the https website, by default, it is restricted by certificate trust and cannot be accessed. There are two solutions: 1. Add the ca certificate of the https website to...

Configure https for nginx and self-signed certificate

November 15, 2016 22:30:47 Reading number: 5518 Configure https for nginx and self-signed certificate 1. Prepare the certificate. To The steps are similar to those described in using OpenSSL to self-i...

Nginx configure https and self-signed certificate

In the past, iOS required all requests to be https for security reasons, and the process of configuring https in the project was recorded. Configure the certificate file in NginxConfiguration in Nginx...

Self-signed certificate configure https (intimately effective)

First, you need the version of OpenSSL to 1.0.0 Viewing the version on the server: OpenSSL Version Second, install OpenSSL-1.0.0 (1) will be renamed / usr / bin / under the openssl file removed or del...

Https request verification certificate failure solution! (trust all certificates)

Error to find valid certification path to requested target Solution: 1, import the certificate to the local certificate store 2, trust all SSL certificates Perhaps the best solution is to trust all SS...

More Recommendation

Android + HTTPSURLCONNECTION + HTTPS certificate authentication and all certificates

First, certificate certification 1, browser download server.cer certificate added to Assets 2, network access Second, trust all certificates 2. Use when network access  ...

HTTPS self-signed certificate and Android client verification

HTTPS self-signed certificate and Android client verification Use openssl to generate self-signed certificate Generate your own root certificate Generate server certificate Configure server certificat...

Android HTTPS self-signed certificate authentication (two)

Use okhttp framework two-way authentication Use okhttp framework two-way authentication 1 Generate client certificate library and certificates 2 configure the server 3 Android configuration In the pre...

Android HTTPS self-signed certificate authentication (1)

Use okhttp framework one-way authentication Use okhttp framework one-way authentication 1 Generate a self-signed certificate 2 Tomcat configuration 3 Android development In view of the continuous upda...

HTTPS treatment with self-signed certificates

This article: OpenSSL (Secretary Certificate Build Tool), Docker, Docker-Compose Create a self-visa book using OpenSSL Create a folder first, use a series of files generated by OpenSSL, switch to the ...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top