在 android 的 okhttp 请求中使用证书

Use a certificate in an okhttp request with android

我工作的应用程序的服务器使用证书来允许请求。 例如,我已将其安装在桌面 Chrome 浏览器中,并且运行良好。这是带有 扩展名 .cer

的普通证书

现在我必须让这个证书在我的 android 应用程序中也起作用,老实说,我从来没有这样做过,我有点迷茫。

为了发出请求,我正在使用 okhttp2,如您在此示例中所见:

 public String makeServiceCall(String url, JSONObject data) {
        final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(45, TimeUnit.SECONDS);
        client.setReadTimeout(45, TimeUnit.SECONDS);
        client.setProtocols(Arrays.asList(Protocol.HTTP_1_1));

        RequestBody body = RequestBody.create(JSON, data.toString());
        Request request = new Request.Builder()
                .url(url)
                .header("Accept","application/json")
                .post(body)
                .build();
        try {
            Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

到目前为止一切正常,但在搜索和阅读教程、示例等之后,(其中许多来自此页面)我还没有成功。使其与证书一起使用。

我从来没有这样做过,已经有点困惑了,希望得到以下澄清:

好的,我已经将我的证书转换为 BKS 并托管在 res/raw 文件夹中,但我仍然无法将其成功应用于请求 okhttp2 ..

我搜索了有关使用 okhttp3 执行此操作的信息,但我也无法授权这些请求。

This article 对我有用,但是我没有用retrofit,适配okhttp2也不行。

如果能解释一下如何操作,我将不胜感激

这是一个使用 official okhttp3 sample code 的实现。可以使用自定义证书创建受信任的 OkHttpClient。我将 .cer 证书放在 res/raw 中,然后使用 trustedCertificatesInputStream() 方法读取它。

CustomTrust customTrust = new CustomTrust(getApplicationContext());
OkHttpClient client = customTrust.getClient();

CustomTrust.java

import android.content.Context;

import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.Arrays;
import java.util.Collection;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import okhttp3.CertificatePinner;
import okhttp3.OkHttpClient;

public final class CustomTrust {

    private final OkHttpClient client;
    private final Context context;

    public CustomTrust(Context context) {

        this.context = context;
        X509TrustManager trustManager;
        SSLSocketFactory sslSocketFactory;
        try {
            trustManager = trustManagerForCertificates(trustedCertificatesInputStream());
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[]{trustManager}, null);
            sslSocketFactory = sslContext.getSocketFactory();
        } catch (GeneralSecurityException e) {
            throw new RuntimeException(e);
        }

        client = new OkHttpClient.Builder()
                .sslSocketFactory(sslSocketFactory, trustManager)
                .connectTimeout(45, TimeUnit.SECONDS)
                .readTimeout(45, TimeUnit.SECONDS)
                .protocols(Arrays.asList(Protocol.HTTP_1_1))
                .build();
    }

    public OkHttpClient getClient() {
        return client;
    }

    /**
     * Returns an input stream containing one or more certificate PEM files. This implementation just
     * embeds the PEM files in Java strings; most applications will instead read this from a resource
     * file that gets bundled with the application.
     */
    private InputStream trustedCertificatesInputStream() {
        return context.getResources().openRawResource(R.raw.certificate);
    }

    /**
     * Returns a trust manager that trusts {@code certificates} and none other. HTTPS services whose
     * certificates have not been signed by these certificates will fail with a {@code
     * SSLHandshakeException}.
     *
     * <p>This can be used to replace the host platform's built-in trusted certificates with a custom
     * set. This is useful in development where certificate authority-trusted certificates aren't
     * available. Or in production, to avoid reliance on third-party certificate authorities.
     *
     * <p>See also {@link CertificatePinner}, which can limit trusted certificates while still using
     * the host platform's built-in trust store.
     *
     * <h3>Warning: Customizing Trusted Certificates is Dangerous!</h3>
     *
     * <p>Relying on your own trusted certificates limits your server team's ability to update their
     * TLS certificates. By installing a specific set of trusted certificates, you take on additional
     * operational complexity and limit your ability to migrate between certificate authorities. Do
     * not use custom trusted certificates in production without the blessing of your server's TLS
     * administrator.
     */
    private X509TrustManager trustManagerForCertificates(InputStream in)
            throws GeneralSecurityException {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(in);
        if (certificates.isEmpty()) {
            throw new IllegalArgumentException("expected non-empty set of trusted certificates");
        }

        // Put the certificates a key store.
        char[] password = "password".toCharArray(); // Any password will work.
        KeyStore keyStore = newEmptyKeyStore(password);
        int index = 0;
        for (Certificate certificate : certificates) {
            String certificateAlias = Integer.toString(index++);
            keyStore.setCertificateEntry(certificateAlias, certificate);
        }

        // Use it to build an X509 trust manager.
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
                KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, password);
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
                TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
            throw new IllegalStateException("Unexpected default trust managers:"
                    + Arrays.toString(trustManagers));
        }
        return (X509TrustManager) trustManagers[0];
    }

    private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException {
        try {
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            InputStream in = null; // By convention, 'null' creates an empty key store.
            keyStore.load(in, password);
            return keyStore;
        } catch (IOException e) {
            throw new AssertionError(e);
        }
    }

}

虽然已经提供了一个很好且完美的答案,但我想提供一个需要较少自定义代码的替代方案。

InputStream trustedCertificatesAsInputStream = context.getResources().openRawResource(R.raw.certificate);
List<Certificate> trustedCertificates = CertificateUtils.loadCertificate(trustedCertificatesAsInputStream);

SSLFactory sslFactory = SSLFactory.builder()
          .withTrustMaterial(trustedCertificates)
          .build();

SSLSocketFactory sslSocketFactory = sslFactory.getSslSocketFactory();
X509ExtendedtrustManager trustManager = sslFactory.getTrustManager().orElseThrow();

OkHttpClient okHttpClient = OkHttpClient.Builder()
          .sslSocketFactory(sslSocketFactory, trustManager)
          .build();

上面的库是我维护的,你可以在这里找到它:GitHub - SSLContext Kickstart