如何使用X509TrustManager验证android.net.http.SslCertificate? [英] How do I validate an android.net.http.SslCertificate with an X509TrustManager?
问题描述
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
方法添加到功能请求作为问题36984840 .
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屋!