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?