我正在尝试将自签名证书导入Keystore。我将cert放在资产文件夹中,并尝试在CertificateFactory中读取输入流。

但是CertificateFactory对象为null。它无法读取输入流。 Inputstream具有价值,我可以检查一下。请在这里查看我的代码:

CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
        AssetManager assetManager = getAssets();
        InputStream caInput = assetManager.open("somecert.pem");
        X509Certificate caCertificate = (X509Certificate)cf.generateCertificate(caInput);
 //  Certificate ca = cf.generateCertificate(caInput);  //Also did this.


caCertificate具有空值。我正在尝试在我的密钥库中使用它。

        String keyStoreType = KeyStore.getDefaultType();
        keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(null, null);
        keyStore.setCertificateEntry("ca", caCertificate);

最佳答案

当我需要上传证书crt时,请使用以下代码(该代码可以为您提供服务,我认为它是相同的):

// Loading the certificate in asserts
CertificateFactory cf = CertificateFactory.getInstance("X.509");
AssetManager assManager = context.getAssets();
caInput = assManager.open("certif.crt");
Certificate ca = cf.generateCertificate(caInput);
// Create a KeyStore containing different CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);

// Create a TrustManager to store certificates
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);

// Creates a context for use ssl certificate
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);


但是在这个问题上可能找到解决方法
How to Load RSA Private Key From File

关于android - CertificateFactory无法从InputStream生成证书,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29234245/

10-15 04:32