Android 内验证Https证书问题

Android P移除BC相关的算法,可以使用AndroidOpenSSL
java.security.cert.CertificateException: X.509 not found
Caused by: java.security.NoSuchAlgorithmException: The BC provider no longer provides an implementation for CertificateFactory.X.509.  Please see https://android-developers.googleblog.com/2018/03/cryptography-changes-in-android-p.html for more details.

CertificateFactory certificateFactory;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
    //适配Android P及以后版本,否则报错NoSuchAlgorithmException
    certificateFactory = CertificateFactory.getInstance("X.509", "AndroidOpenSSL");//
} else {
    certificateFactory = CertificateFactory.getInstance("X.509", "BC");
}
//CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509","BC");//, "BC"
Logger.e("TAG", " certificates.length: " + certificates.length);


//CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate ca = certificateFactory.generateCertificate(certificates[0]);
pinningPublicKey = new BigInteger(1, ca.getPublicKey().getEncoded()).toString(16);
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, null);
keyStore.setCertificateEntry("certificateAlias", ca);
for (InputStream certificate : certificates) {
    try {
        if (certificate != null)
            certificate.close();
    } catch (IOException e) {
    }
}
TrustManagerFactory trustManagerFactory = null;
trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

 

java.security.cert.CertificateException: com.android.org.conscrypt.OpenSSLX509CertificateFactory$ParsingException: com.android.org.conscrypt.OpenSSLX509CertificateFactory$ParsingException: inStream is empty
如果用Certificate ca = certificateFactory.generateCertificate(certificates[0]);的时候

再次keyStore.setCertificateEntry("certificateAlias", certificateFactory.generateCertificate(certificates[0]));就会出现上面错误

keyStore.setCertificateEntry("certificateAlias", ca); 就没有问题

顺带记录下问题

你可能感兴趣的:(Android,常见问题)