最近我实现了一项安全功能来检查我的请求是否与有效主机连接。为此,我正在检查该主机的证书,并在这种情况下使用了 X509TrustManager。因此,如果 X509TrustManager 发现一些无效证书,它将引发异常,据此,我将向用户显示警报。但问题是 X509TrustManager 仅在第一次抛出异常。但是当我刷新相同的请求时,我没有发现无效的认证,也没有看到任何警报。下面我添加了我的实现。让我知道我的实现的任何问题或 X509TrustManager 的任何已知问题。谢谢并恭祝安康。
final X509TrustManager finalTrustManager = x509TrustManager;
TrustManager[] trustAllCerts = new TrustManager[0];
if (finalTrustManager != null) {
trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return finalTrustManager.getAcceptedIssuers();
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
try {
// If Application get any CertificateException in Splash screen we will show related alert in MainActivity
// We need to terminate app after showing alert but if we show alert in Splash screen it will get hide when Main Activity get visible.
// To avoid this scenario we added this implementation.
if (mIsSplashGetInvalidateCertificate && !(mLifecycleManager.getCurrentStackOfActivity().get(0) instanceof SplashActivity)) {
mAlertManager.showAlertMessageWithoutDuplicates(mLifecycleManager.getCurrentContext().getResources().getString(R.string.certificate_error_title), mLifecycleManager.getCurrentContext().getResources().getString(R.string.certificate_error_message), (FragmentActivity) mLifecycleManager.getCurrentStackOfActivity().get(0), true);
}
// Checking the certificate availability of host
if ((certs != null && certs.length != 0) && (authType != null && authType.length() != 0)) {
finalTrustManager.checkClientTrusted(certs, authType);
} else {
terminateApplicationWithAlert();
}
} catch (CertificateException e) {
terminateApplicationWithAlert();
}
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
try {
if (mIsSplashGetInvalidateCertificate && !(mLifecycleManager.getCurrentStackOfActivity().get(0) instanceof SplashActivity)) {
mAlertManager.showAlertMessageWithoutDuplicates(mLifecycleManager.getCurrentContext().getResources().getString(R.string.certificate_error_title), mLifecycleManager.getCurrentContext().getResources().getString(R.string.certificate_error_message), (FragmentActivity) mLifecycleManager.getCurrentStackOfActivity().get(0), true);
}
if ((certs != null && certs.length != 0) && (authType != null && authType.length() != 0)) {
finalTrustManager.checkServerTrusted(certs, authType);
} else {
terminateApplicationWithAlert();
}
} catch (CertificateException e) {
terminateApplicationWithAlert();
}
}
}
};
}