title: How to generate RSA KeyPair OpenSSH format in JAVA
body: <p>I am trying to generate RSA keypair within JAVA. So far able to generate them but not in desired format. I had similar Python script which gives correct result as per my requirement. Must be missing some encoding.</p>
  <pre class="lang-java prettyprint-override"><code>KeyPairGenerator generator = KeyPairGenerator.getInstance(&quot;RSA&quot;);
  generator.initialize(2048);
  KeyPair kp = generator.generateKeyPair();
  PublicKey publicKey = kp.getPublic();
  PrivateKey privateKey = kp.getPrivate();
  String private_key = Base64.getMimeEncoder().encodeToString(publicKey.getEncoded());
  String public_key = Base64.getMimeEncoder().encodeToString(privateKey.getEncoded());
  </code></pre>
  <p>Here is Python script sample which generate required format well.</p>
  <pre class="lang-py prettyprint-override"><code>key = rsa.generate_private_key(
          backend=crypto_default_backend(),
          public_exponent=65537,
          key_size=2048
      )
  private_key_bytes = key.private_bytes(
          crypto_serialization.Encoding.PEM,
          crypto_serialization.PrivateFormat.OpenSSH,
          crypto_serialization.BestAvailableEncryption(bytes(private_key_secret, 'utf-8')))
  
  public_key_bytes = key.public_key().public_bytes(
          crypto_serialization.Encoding.OpenSSH,
          crypto_serialization.PublicFormat.OpenSSH
      )
  private_key = private_key_bytes.decode(&quot;utf-8&quot;)
  public_key = public_key_bytes.decode(&quot;utf-8&quot;)
  
  </code></pre>