当安卓客户端与服务器建立https连接时,需要验证服务器是否具备平台已知的CA证书。由于服务器的CA证书可能无法被安卓系统识别,有可能出现下面的异常:
javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
谷歌官方也给出了这个问题的详细介绍,解决的方法是通过加载证书文件,创建一个KeyStore,用来初始化TrustManager,用来信任加载的CA证书。再通过SSLContext将这个证书集替换默认的sslSocketFactory。
今天提出一个简单的证书集工具类,可方便管理自己的证书集。
public class CustomTrustManager {
protected static X509TrustManager trustManager;
protected static SSLSocketFactory sslSocketFactory;
private CustomTrustManager() {
try {
//读取证书文件,可用字符串流或文件
trustManager = trustManagerForCertificates(trustedCertificatesInputStream());
SSLContext sslContext = SSLContext.getInstance("TLS");
//使用sslContext将自定义证书集初始化
sslContext.init(null, new TrustManager[]{trustManager}, null);
sslSocketFactory = sslContext.getSocketFactory();
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
}
//内部静态类的单例模式
private static class CustomTrustHolder {
private static final CustomTrustManager INSTANCE = new CustomTrustManager();
}
public X509TrustManager getTrustManager(){
return CustomTrustHolder.INSTANCE.trustManager;
}
public SSLSocketFactory getSSLSocketFactory(){
return CustomTrustHolder.INSTANCE.sslSocketFactory;
}
public static CustomTrustManager getInstance() {
return CustomTrustHolder.INSTANCE;
}
//用来创建证书和证书集,替换当前平台的证书集
//如果需要补授信某些服务器,可是使用CertificatePinner
private static X509TrustManager trustManagerForCertificates(InputStream in) throws
GeneralSecurityException {
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
Collection<? extends Certificate> certificates = certificateFactory.generateCertificates
(in);
if (certificates.isEmpty()) {
throw new IllegalArgumentException("expected non-empty set of trusted certificates");
}
//指定一个密码
char[] password = "password".toCharArray();
KeyStore keyStore = newEmptyKeyStore(password);
int index = 0;
for (Certificate certificate : certificates) {
String certificateAlias = Integer.toString(index++);
keyStore.setCertificateEntry(certificateAlias, certificate);
}
//初始化X509TrustManager
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, password);
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
throw new IllegalStateException("Unexpected default trust managers:"
+ Arrays.toString(trustManagers));
}
return (X509TrustManager) trustManagers[0];
}
private static KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException {
try {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream in = null; // By convention, 'null' creates an empty key store.
keyStore.load(in, password);
return keyStore;
} catch (IOException e) {
throw new AssertionError(e);
}
}
//使用jdk的keytool命令读取证书内容 keytool -printcert -rfc -file 证书名.cer
private static InputStream trustedCertificatesInputStream() {
//示例,此处替换从网站下载的CA证书
String certA =
"-----BEGIN CERTIFICATE-----\n" +
“dLZzF2JaIn4LAmtQrFSM2sNRis\n" +
"-----END CERTIFICATE-----";
String certB = ...
return new Buffer()
.writeUtf8(CertA)
//可指定多个证书
.writeUtf8(CertB)
.inputStream();
}
}
在Chrome浏览器的开发者模式中,可以下载到https网站的证书。
然后使用jdk的keytool命令复制证书内容,替换trustedCertificatesInputStream方法中的字符串。
使用这个工具类,可以非常方便的使用自签名或者非认证的证书与服务器进行https连接。