2

I'm trying to do the equivalent of the following commands, but in Java:

openssl genrsa -out privatekey.pem 1024
openssl req -newkey rsa:1024 -x509 -key privatekey.pem -out publickey.cer -days 365 
openssl pkcs8 -topk8 -nocrypt -in privatekey.pem -out privatekey.pcks8

I have the following code, which I understand generates both keys in pcks8 format, but how do I get the public key output in the same format as above? What else am I missing?

KeyPairGenerator keyGen = null;
try {
  keyGen = KeyPairGenerator.getInstance("RSA");
} catch (NoSuchAlgorithmException e) {
  throw new RuntimeException(e);
}
KeyPair pair = keyGen.generateKeyPair();
String privateKey = Base64.encodeBase64String(pair.getPrivate().getEncoded());
String publicKey = Base64.encodeBase64String(pair.getPublic().getEncoded());

Any help is greatly appreciated. This is the first time I've worked with asymmetric keys.

jww
  • 97,681
  • 90
  • 411
  • 885
Doug
  • 6,446
  • 9
  • 74
  • 107
  • That 'format' you refer to is a self-signed X.509 certificate. Java can't generate that without using a third party library, for example the bouncycastle library. – President James K. Polk Feb 01 '15 at 02:02

0 Answers0