如何使用X509TrustManager验证android.net.http.SslCertificate?

时间:2013-11-26 21:55:52

标签: android security android-webview x509certificate

Android WebViewClient在遇到不受信任的证书时调用onReceivedSslError。但是,我在该调用中收到的SslError对象没有任何公开的方式来访问基础X509Certificate以针对现有TrustStoreManager验证它。查看源代码,我可以访问X509Certificate的编码字节:

public void onReceivedSslError(WebView view, SslErrorHandler handler,
        SslError error) {
    Bundle bundle = SslCertificate.saveState(error.getCertificate());
    X509Certificate x509Certificate;
    byte[] bytes = bundle.getByteArray("x509-certificate");
    if (bytes == null) {
        x509Certificate = null;
    } else {
        try {
            CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
            Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(bytes));
            x509Certificate = (X509Certificate) cert;
        } catch (CertificateException e) {
            x509Certificate = null;
        }
    }

    // Now I have an X509Certificate I can pass to an X509TrustManager for validation.
}

显然,这是私有API并且很脆弱,但我认为它相当可靠,因为它们无法更改捆绑包格式。还有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

经过漫长的等待,看来SslCertificate之后已经向feature request as issue 36984840添加了名为getX509Certificate(): java.security.cert.X509Certificate的方法。