如何使用X509TrustManager验证android.net.http.SslCertificate? [英] How do I validate an android.net.http.SslCertificate with an X509TrustManager?

查看:655
本文介绍了如何使用X509TrustManager验证android.net.http.SslCertificate?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Android的WebViewClient在遇到不受信任的证书时会调用onReceivedSslError.但是,我在该调用中收到的SslError对象没有任何公共方式可以访问基础X509Certificate来针对现有的TrustStoreManager进行验证.从源头来看,我可以这样访问X509Certificate的编码字节:

Android's WebViewClient calls onReceivedSslError when it encounters an untrusted cert. However, the SslError object I receive in that call doesn't have any way public way to get to the underlying X509Certificate to validate it against an existing TrustStoreManager. Looking at the source, I can access the X509Certificate's encoded bytes thusly:

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,并且很脆弱,尽管我认为它是相当可靠的,因为他们不能更改包格式.有更好的方法吗?

Obviously, this is private API and is fragile, though I assume it is fairly reliable since they can't change the bundle format. Is there a better way?

推荐答案

经过长时间的等待,似乎已将getX509Certificate(): java.security.cert.X509Certificate方法添加到

After a long wait it seems that a method called getX509Certificate(): java.security.cert.X509Certificate has been added to SslCertificate after my feature request as issue 36984840.

这篇关于如何使用X509TrustManager验证android.net.http.SslCertificate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆