Certificate certificate;
CertificateFactory cf = null;
try {
cf = CertificateFactory.getInstance("X.509");
InputStream caInput = getResources().openRawResource(R.raw.cert);
certificate = cf.generateCertificate(caInput);
caInput.close();
} catch (CertificateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
添加 onReceivedSslError 如下。使用 url 使用的证书检查原始文件中的证书,以便您使用cert.verify 验证它
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
SslCertificate sslCertificate = error.getCertificate();
Certificate cert = getX509Certificate(sslCertificate);
if (cert != null && certificate != null){
try {
cert.verify(certificate.getPublicKey());
handler.proceed();
} catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException | SignatureException e) {
super.onReceivedSslError(view, handler, error);
handler.cancel();
e.printStackTrace();
}
} else {
super.onReceivedSslError(view, handler, error);
}
super.onReceivedSslError(view, handler, error);
}
如下图添加生成证书的代码函数
private Certificate getX509Certificate(SslCertificate sslCertificate) {
Bundle bundle = SslCertificate.saveState(sslCertificate);
byte[] bytes = bundle.getByteArray("x509-certificate");
if (bytes == null) {
return null;
} else {
try {
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
return certFactory.generateCertificate(new ByteArrayInputStream(bytes));
} catch (CertificateException e) {
return null;
}
}
}
要正确处理 SSL 证书验证,请更改代码以在服务器提供的证书符合您的期望时调用 SslErrorHandler.proceed(),否则调用 SslErrorHandler.cancel()。包含受影响应用和类的电子邮件警报已发送至您的开发者帐户地址。
如果您使用 onReceivedSslError 上传您的应用并使用 handler.proceed 而不检查证书,这就是谷歌安全警报将显示的内容。
希望对你有帮助!!