java - 如何在 Java 中将 pkcs8 转换为 pkcs12

标签 java pkcs#12 pkcs#8

我知道这可以通过 openssl 实现。 但我想知道是否有使用任何库在 Java 中转换 PKCS 的可能性(pkcs8 到 12)。

最佳答案

首先,您将 PKCS#8 编码的 key 作为文件读取并创建 PrivateKey 对象

public PrivateKey loadPrivateKey(String keyFile)
    throws Exception {

    File f = new File(keyFile);
    FileInputStream fis = new FileInputStream(f);
    DataInputStream dis = new DataInputStream(fis);
    byte[] keyBytes = new byte[(int) f.length()];
    dis.readFully(keyBytes);
    dis.close();
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return kf.generatePrivate(spec);
}

然后这个 key 被保存到 PKCS#12 keystore 中

public void createKeyStore(String keyStorePwd, String keyStoreFile,
    PrivateKey privateKey, X509Certificate certificate)
    throws Exception {

    char[] pwd = keyStorePwd.toCharArray();

    KeyStore ks = KeyStore.getInstance("PKCS12");
    ks.load(null, pwd);

    KeyStore.ProtectionParameter protParam =
        new KeyStore.PasswordProtection(pwd);
    Certificate[] certChain =
        new Certificate[]{ certificate };
    KeyStore.PrivateKeyEntry pkEntry =
        new KeyStore.PrivateKeyEntry(privateKey, certChain);
    ks.setEntry("keypair", pkEntry, protParam);

    FileOutputStream fos = new FileOutputStream(keyStoreFile);
    ks.store(fos, pwd);
    fos.close();
}

关于java - 如何在 Java 中将 pkcs8 转换为 pkcs12,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21832338/

相关文章:

java - 如何读取.pem文件来获取私钥和​​公钥

private-key - java中将私钥转换为PKCS#8格式

java - java中的信号量阻塞

java - 使用java套接字编程查询文件传输

ssl - 如何使用公钥隐私/完整性模式验证 PFX

openssl - 在没有导出密码的情况下导出 PKCS#12 文件?

Java keystore 加载第一次工作,第二次抛出错误

java - Selenium 无法通过 id 找到元素

java - 将 JPanel 保存为 png 文件

java - 从编码的私钥字节中提取算法 ID