title: Generate RSA Keys Perform KeyPairGenerator x509
body: <p>I'm trying to do the equivalent of the following commands, but in Java:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>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?</p>
  
  <pre><code>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());
  </code></pre>
  
  <p>Any help is greatly appreciated. This is the first time I've worked with asymmetric keys. </p>