I think you can try as the following:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
WebView webView = (WebView) findViewById(R.id.webView);
if (webView != null) {
// Get cert from raw resource...
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream caInput = getResources().openRawResource(R.raw.rootca); // stored at appsrcmain
es
aw
final Certificate certificate = cf.generateCertificate(caInput);
caInput.close();
String url = "https://www.yourserver.com";
webView.setWebViewClient(new WebViewClient() {
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
// Get cert from SslError
SslCertificate sslCertificate = error.getCertificate();
Certificate cert = getX509Certificate(sslCertificate);
if (cert != null && certificate != null){
try {
// Reference: https://developer.android.com/reference/java/security/cert/Certificate.html#verify(java.security.PublicKey)
cert.verify(certificate.getPublicKey()); // Verify here...
handler.proceed();
} catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException | SignatureException e) {
super.onReceivedSslError(view, handler, error);
e.printStackTrace();
}
} else {
super.onReceivedSslError(view, handler, error);
}
}
});
webView.loadUrl(url);
}
} catch (Exception e){
e.printStackTrace();
}
}
// credits to @Heath Borders at http://stackoverflow.com/questions/20228800/how-do-i-validate-an-android-net-http-sslcertificate-with-an-x509trustmanager
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;
}
}
}
If failed validation, logcat will have some information such as java.security.SignatureException: Signature was not verified...
If success, here's a screenshot:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…