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并且很脆弱,但我认为它相当可靠,因为它们无法更改捆绑包格式。还有更好的方法吗?
答案 0 :(得分:1)
经过漫长的等待,看来SslCertificate
之后已经向feature request as issue 36984840添加了名为getX509Certificate(): java.security.cert.X509Certificate
的方法。