需要帮助理解getAcceptedIssuers方法

时间:2014-07-19 18:52:29

标签: java android x509certificate

我正在编写代码以从Android设备获取所有可信证书。

这是我的代码,

public class MyX509TrustManager implements X509TrustManager {
X509TrustManager pkixTrustManager;

public MyX509TrustManager(KeyStore keystore)
        throws Exception {

    TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
    tmf.init(keystore);

    TrustManager tms[] = tmf.getTrustManagers();

    for (int i = 0; i < tms.length; i++) {
        if (tms[i] instanceof X509TrustManager) {
            pkixTrustManager = (X509TrustManager) tms[i];

            System.out.println("The class is " + pkixTrustManager.getClass());
            return;
        }
    }

    throw new Exception("Couldn't initialize");
}

public void checkClientTrusted(X509Certificate[] arg0, String arg1)
        throws CertificateException {

    try {
        pkixTrustManager.checkClientTrusted(arg0, arg1);
    } catch (CertificateException excep) {

    }

}

public void checkServerTrusted(X509Certificate[] arg0, String arg1)
        throws CertificateException {
    // TODO Auto-generated method stub
    try {
        pkixTrustManager.checkServerTrusted(arg0, arg1);
    } catch (CertificateException excep) {

    }
}

public X509Certificate[] getAcceptedIssuers() {


    System.out.println("Control inside the issuers method");

    System.out.println( "Number of trusted certificates is "+   pkixTrustManager.getAcceptedIssuers().length);
    return pkixTrustManager.getAcceptedIssuers();

}
}

当我调用getAcceptedIssuers方法时,我得到空数组(由getacceptedIssuers方法返回的数组长度确认)

我在这里做错了什么。

任何人都可以帮我解决这个问题,以获取Android设备的可信证书列表。

修改

我在另一个类中调用MyX509TrustManager的构造函数:

KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
// KeyStore.getDefaultType() returns "BKS"

MyX509TrustManager mm = new MyX509TrustManager(ks);

X509Certificate [] trucerts = m.getAcceptedIssuers();

如何使用可信证书加载密钥库?

1 个答案:

答案 0 :(得分:1)

您在调用构造函数MyX509TrustManager(KeyStore keystore)时提供的密钥库没有为任何证书颁发机构持有任何证书。

例如,您可以创建一个KeyStore对象,并用文件系统中密钥库的内容(密钥,证书,CA证书......)填充它:

KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());

// get user password and file input stream
char[] password = "password of the keystore in the file system";

java.io.FileInputStream fis = null;
try {
    fis = new java.io.FileInputStream("keyStoreName");
    ks.load(fis, password);
} finally {
    if (fis != null) {
        fis.close();
    }
}