最近实现了一个安全特性来检查我的请求是否与有效的主机连接。为此,我正在检查该主机的证书,并在这个情况下使用了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();
}
}
}
};
}发布于 2020-02-04 04:44:09
实际上,您并没有将证书标记为无效,因为您正在捕获并吞服CertificateException。通过不抛出CertificateException,您可以告诉HTTP无效证书是有效的,这大概是为了不多次重新验证证书。
您需要允许从CertificateException方法抛出X509TrustManager,捕捉HTTP站点上的错误,并在那里显示对话框。
https://stackoverflow.com/questions/60050562
复制相似问题