5

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?

Simon Kissane
  • 4,373
  • 3
  • 34
  • 59

1 Answers1

7

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));
}
President James K. Polk
  • 40,516
  • 21
  • 95
  • 125