如何在Java中将pkcs8转换为pkcs12

时间:2014-02-17 14:59:47

标签: java pkcs#12 pkcs#8

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

1 个答案:

答案 0 :(得分:2)

首先,您将PKCS#8编码密钥作为文件读取并创建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);
}

然后将此密钥保存到PKCS#12密钥库

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();
}