问题
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