如何将 PKCS12 证书存储到 Android KeyStore?

时间:2021-02-24 16:35:07

标签: java android react-native client-certificates

我有一个 PKCS12 证书,它是从 API 返回的密码保护(编码)。 我想将该证书导入或存储到 Android KeyStore。

 @RequiresApi(api = Build.VERSION_CODES.O)
private void getCertsFromP12(String cert, String passphrase){
    try {
        KeyStore p12 = KeyStore.getInstance("pkcs12");
        byte[] decoded = Base64.getDecoder().decode(cert);
        InputStream is = new ByteArrayInputStream(decoded);
        p12.load(is, passphrase.toCharArray());
        Enumeration e = p12.aliases();
        while (e.hasMoreElements()) {
            String alias = (String) e.nextElement();
            System.out.println(alias);
            X509Certificate c = (X509Certificate) p12.getCertificate(alias);
            System.out.println(c);
            addCertificateToKeyStore(c);
        }
    } catch (Exception e) {
        System.out.println("CERT ERROR: " + e);
    }
}

private void addCertificateToKeyStore(X509Certificate c) {
    try {
        KeyStore ks = KeyStore.getInstance("AndroidKeyStore");
        ks.load(null);
        ks.setCertificateEntry("alias",  c);
        String test = ks.getCertificateAlias(c);
    } catch (Exception e){
        System.out.println("CERT ERROR: " + e);
    }
}

我没有收到任何错误,但是当我在设备的“设置”中预览我的用户证书时 - 它是空的。我刚开始使用 KeyStore。

KeyStore.store()

似乎这是我需要的,但这需要来自文件的输出流。我没有文件,只有一个以字符串形式返回的编码证书。

我错过了什么或不明白什么? 我设法在 iOS 上实现了相同的目标,但要简单得多。

0 个答案:

没有答案
相关问题