【问题标题】:Request with automatic or user selection of appropriate client certificate请求自动或用户选择适当的客户端证书
【发布时间】:2017-12-09 07:46:37
【问题描述】:

我正在开发一个可以连接到不同服务器的混合 cordova 应用程序。其中一些确实需要客户端证书。

在 Android 手机上安装了相应的根证书 + 客户端证书。

在 Chrome 浏览器上,我得到以下对话框,为 Web 连接选择相应的客户端证书。

使用 cordova 插件 cordova-client-cert-authentication 会弹出相同的对话框,用于 WebView 中的 Http(s) 请求。

我的问题是如何在 原生 Android 平台上实现对 Http(s) 请求的自动证书选择,而无需明确声明相应的客户端证书。或者是否有类似于用户选择证书的功能,例如在 Chrome 上实现的?

这是当前的实现,它会引发握手异常:

try {
    URL url = new URL( versionUrl );
    HttpsURLConnection urlConnection = ( HttpsURLConnection ) url.openConnection();

    urlConnection.setConnectTimeout( 10000 );

    InputStream in = urlConnection.getInputStream();
}
catch(Exception e)
{
    //javax.net.ssl.SSLHandshakeException: Handshake failed
}

【问题讨论】:

  • 您想使用之前安装在Android KeyChain(系统密钥库)中的证书还是直接将证书提供给HttpsURLConnection?
  • 我想使用之前安装的 KeyChain 证书。它是使用凭据安装的“VPN 和应用程序”

标签: java android ssl ssl-certificate client-certificates


【解决方案1】:

您可以使用之前安装在Android KeyChain(系统密钥库)中的证书扩展X509ExtendedKeyManager来配置URLConnection使用的SSLContext

证书由您需要的别名引用。提示用户使用类似于 chrome 的对话框进行选择:

KeyChain.choosePrivateKeyAlias(this, this, // Callback
            new String[] {"RSA", "DSA"}, // Any key types.
            null, // Any issuers.
            null, // Any host
            -1, // Any port
            DEFAULT_ALIAS);

这是使用自定义 KeyManager 配置 SSL 连接的代码。它使用默认的TrustManager 和HostnameVerifier。如果服务器使用的是 Android 默认信任库中不存在的自签名证书,则需要配置它们(不建议信任所有证书)

//Configure trustManager if needed
TrustManager[] trustManagers = null;

//Configure keyManager to select the private key and the certificate chain from KeyChain
KeyManager keyManager = KeyChainKeyManager.fromAlias(
            context, mClientCertAlias);

//Configure SSLContext
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(new KeyManager[] {keyManager}, trustManagers, null);


//Perform the connection
URL url = new URL( versionUrl );
HttpsURLConnection urlConnection = ( HttpsURLConnection ) url.openConnection();
urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());
//urlConnection.setHostnameVerifier(hostnameVerifier);  //Configure hostnameVerifier if needed
urlConnection.setConnectTimeout( 10000 );
InputStream in = urlConnection.getInputStream();

最后,您拥有从负责选择客户端证书的here 和here 中提取的自定义X509ExtendedKeyManager 的完整实现。我已经提取了所需的代码。

public static class KeyChainKeyManager extends X509ExtendedKeyManager {
    private final String mClientAlias;
    private final X509Certificate[] mCertificateChain;
    private final PrivateKey mPrivateKey;

        /**
         * Builds an instance of a KeyChainKeyManager using the given certificate alias.
         * If for any reason retrieval of the credentials from the system {@link android.security.KeyChain} fails,
         * a {@code null} value will be returned.
         */
        public static KeyChainKeyManager fromAlias(Context context, String alias)
                throws CertificateException {
            X509Certificate[] certificateChain;
            try {
                certificateChain = KeyChain.getCertificateChain(context, alias);
            } catch (KeyChainException e) {
                throw new CertificateException(e);
            } catch (InterruptedException e) {
                throw new CertificateException(e);
            }

            PrivateKey privateKey;
            try {
                privateKey = KeyChain.getPrivateKey(context, alias);
            } catch (KeyChainException e) {
                throw new CertificateException(e);
            } catch (InterruptedException e) {
                throw new CertificateException(e);
            }

            if (certificateChain == null || privateKey == null) {
                throw new CertificateException("Can't access certificate from keystore");
            }

            return new KeyChainKeyManager(alias, certificateChain, privateKey);
        }

        private KeyChainKeyManager(
                String clientAlias, X509Certificate[] certificateChain, PrivateKey privateKey) {
            mClientAlias = clientAlias;
            mCertificateChain = certificateChain;
            mPrivateKey = privateKey;
        }


        @Override
        public String chooseClientAlias(String[] keyTypes, Principal[] issuers, Socket socket) {
            return mClientAlias;
        }

        @Override
        public X509Certificate[] getCertificateChain(String alias) {
            return mCertificateChain;
        }

        @Override
        public PrivateKey getPrivateKey(String alias) {
            return mPrivateKey;
        }

         @Override
        public final String chooseServerAlias( String keyType, Principal[] issuers, Socket socket) {
            // not a client SSLSocket callback
            throw new UnsupportedOperationException();
        }

        @Override
        public final String[] getClientAliases(String keyType, Principal[] issuers) {
            // not a client SSLSocket callback
            throw new UnsupportedOperationException();
        }

        @Override
        public final String[] getServerAliases(String keyType, Principal[] issuers) {
            // not a client SSLSocket callback
            throw new UnsupportedOperationException();
        }
    }
}

我没有测试它。报告任何错误!

【讨论】:

【解决方案2】:

如果您的 URL 仍处于开发阶段(不是生产版本),您可以跳过那些 SSL/NON-SSL 证书安装以访问 URL。

以下是如何跳过 SSL 验证: 在活动 onCreate() 或访问 URL 之前需要的地方调用。

public static void skipSSLValidation() {
        try {
            TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        public X509Certificate[] getAcceptedIssuers() {
                    /* Create a new array with room for an additional trusted certificate. */
                            return new X509Certificate[0];
                        }

                        @Override
                        public void checkClientTrusted(X509Certificate[] certs, String authType) {
                        }

                        @Override
                        public void checkServerTrusted(X509Certificate[] certs, String authType) {
                        }
                    }
            };

            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String arg0, SSLSession arg1) {
                    return true;
                }
            });
        } catch (Exception e) {
            // pass
        }
    }

注意:如果您的 HTTPS URL 有效,则无需使用服务器生成的证书。您应该将此方法仅用于测试/开发。对于发布/生产,您不必使用此方法。

【讨论】:

  • 此解决方案无效。跳过服务器证书验证意味着客户端将信任任何证书,但服务器仍然需要客户端提供证书进行身份验证。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多