了解 SSL 信任策略
Understanding the SSL Trust Strategy
我正在努力理解 TrustStrategy is to adopt for the method loadTrustMaterial。
public SSLContextBuilder loadTrustMaterial(KeyStore truststore,
TrustStrategy trustStrategy)
throws NoSuchAlgorithmException,
KeyStoreException
我找到了四个不同的例子,我很好奇这四个之间的区别,因为描述太少,无法理解differences/usages/advantages/disadvantages。
以下是四个不同的代码示例:
TrustStrategy:看起来我们在这里覆盖了标准的 JSSE 证书验证过程,但它总是返回 true 那么它是否也信任无效证书?
TrustStrategy trustStrategy = new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String authType) throws CertificateException {
return true;
}
};
SSLContextBuilder sslContextBuilder = SSLContexts.custom()
.loadTrustMaterial(trustStore, trustStrategy);
NULL:我们没有给出任何策略,它会做什么?
SSLContextBuilder sslContextBuilder = SSLContexts.custom()
.loadTrustMaterial(trustStore, null);
TrustAllStrategy:它会信任所有签名的证书,那么安全吗?
SSLContextBuilder sslContextBuilder = SSLContexts.custom()
.loadTrustMaterial(trustStore, new TrustAllStrategy());
TrustSelfSignedStrategy:这个和 TrustAllStrategy 有什么区别?
SSLContextBuilder sslContextBuilder = SSLContexts.custom()
.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy());
请帮我理解这四个版本的示例之间的区别,好吗?提前致谢。
首先,强烈建议不要信任所有证书。而是将证书添加到信任库。
TrustStategy
是一个接口,由一些类型实现。
这里所有这些方法都来自 apache httpclient
- 第一个(覆盖 isTrusted 方法)或多或少等于 TrustAllStrategy
并且只是创建一个自定义实例 TrustStrategy
您可以在其中定义自己的方式来确定证书是否受信任。
在此处查看 TrustAllStrategy
的源代码:
public class TrustAllStrategy implements TrustStrategy {
public static final TrustAllStrategy INSTANCE = new TrustAllStrategy();
@Override
public boolean isTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
return true;
}
将 TrustStrategy
设置为 null 将导致没有任何 TrustManager
:
public SSLContextBuilder loadTrustMaterial(
final KeyStore truststore,
final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException {
final TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(
trustManagerFactoryAlgorithm == null ? TrustManagerFactory.getDefaultAlgorithm()
: trustManagerFactoryAlgorithm);
tmfactory.init(truststore);
final TrustManager[] tms = tmfactory.getTrustManagers();
if (tms != null) {
if (trustStrategy != null) {
for (int i = 0; i < tms.length; i++) {
final TrustManager tm = tms[i];
if (tm instanceof X509TrustManager) {
tms[i] = new TrustManagerDelegate(
(X509TrustManager) tm, trustStrategy);
}
}
}
for (final TrustManager tm : tms) {
this.trustManagers.add(tm);
}
}
return this;
}
TrustSelfSignedStrategy
的工作原理如下:
@Override
public boolean isTrusted(
final X509Certificate[] chain, final String authType) throws CertificateException {
return chain.length == 1;
}
自签名证书由证书对象颁发。它在许多应用程序中默认生成,通常用于内部网。