Can JcaPEMWriter generate PKCS#8 output?

一曲冷凌霜 提交于 2020-06-16 03:37:31

问题


The following code uses the JcaPEMWriter class from BouncyCastle to output a randomly generated RSA private key in PKCS#1 format (-----BEGIN RSA PRIVATE KEY-----):

public static void main(String[] args) throws Exception {
    final KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(2048, null);
    final KeyPair kp = kpg.generateKeyPair();
    final PrivateKey privateKey = kp.getPrivate();
    final StringWriter s = new StringWriter();
    try (JcaPEMWriter w = new JcaPEMWriter(s)) {
        w.writeObject(privateKey);
    }
    System.out.println(s);
}

Is there any way to make JcaPEMWriter output PKCS#8 format (-----BEGIN PRIVATE KEY-----) instead?


回答1:


You need to supply a slightly different object to the PEMWriter, namely a JcaPKCS8Generator. The following should work

try (JcaPEMWriter w = new JcaPEMWriter(s)) {
    w.writeObject(new JcaPKCS8Generator(privateKey, null));
}


来源:https://stackoverflow.com/questions/50324046/can-jcapemwriter-generate-pkcs8-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!