无法将从String生成的证书添加到我的自定义TrustManagers

时间:2016-04-20 19:42:21

标签: java android x509certificate

我试图创建一个使用从Base64编码的PEM字符串解码的CA证书填充的TrustManagers数组,以便在SSLSocketFactory中传递它。这是我的代码:

public static TrustManager[] getCustomTrustManagers(List<CertObject> certObjects)
{
    TrustManagerFactory tmf;
    try
    {
        tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

        if (AndroidBuild.getSdkVersion() >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH)
        {
            KeyStore trustStore;
            try
            {
                trustStore = KeyStore.getInstance("BKS", "BC");
                trustStore.load (null, null);
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                for (CertObject certObject : certObjects)
                {
                    byte[] decoded = org.apache.commons.codec.binary.Base64.decodeBase64(certObject.getData().getBytes());
                    Certificate cert = cf.generateCertificate(new ByteArrayInputStream(decoded));
                    trustStore.setCertificateEntry(certObject.getName(), cert);
                }
            }
            catch (KeyStoreException | NoSuchAlgorithmException | IOException  e)
            {
                trustStore = null;
            }
            tmf.init(trustStore);
        }
        else
        {
            tmf.init((KeyStore) null);
        }
    }
    catch (NoSuchAlgorithmException | KeyStoreException e)
    {
        Log.e(TAG, e.getMessage);
    }

    return tmf.getTrustManagers();
}

证书已成功生成,我看到X509Certificate的有效实例,但随后失败了

trustStore.setCertificateEntry(certObject.getName(), cert);

我有以下错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Object.hashCode()' on a null object reference
  at java.util.Collections.secondaryHash(Collections.java:3405)
  at java.util.Hashtable.get(Hashtable.java:265)
  at com.android.org.bouncycastle.jcajce.provider.keystore.bc.BcKeyStoreSpi.engineSetCertificateEntry(BcKeyStoreSpi.java:638)
  at java.security.KeyStore.setCertificateEntry(KeyStore.java:393)
  at com.xxx.app.core.Utils.getCustomTrustManagers(Utils.java:58)

任何想法有什么不对?我应该如何将证书添加到密钥库? certObject.getName()certObject.getData()都是非空字符串。 certObject.getData()包含使用Base64编码的PEM证书数据,但没有-----BEGIN CERTIFICATE----------END CERTIFICATE-----行。

提前致谢!

1 个答案:

答案 0 :(得分:1)

尝试使用不同的别名certObject.getName()看起来为空。

trustStore.setCertificateEntry("MyAlias", cert);

MyAlias你必须用一些动态字符串替换。我只是作为一个例子。