title: How do I convert an RSA public key to an ssh-rsa public key in Java?
body: <p>I have the following public key (as an example):</p>
  
  <pre><code>-----BEGIN PUBLIC KEY-----
  MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjKAmiieDC6SEYpxdI5Kn
  iRUmUwE5EQL2nyDNDrV4dpC28mIcvKlCHWrq8YL7vpKya5GRUYl5xFNoB73s0UGn
  8AtZBlG82/vbAPI5g9OoF2Df+0PusG5da+yFZXJNIyx1Kmgp4Ca4BR4WHGYo2LiW
  zvhjCi9OBO6ERFrlCX1tGCI8mVxo54PzSMbo6LxYmJcJgUneVERjmQe1+tvggeP5
  J44xJB5ompRkXg3VEeqYiqC8RfU3cL2DxTLsQqz/ndtpyGwjd1VCreXZCveDJlHN
  WDZHvaHIReJa4aQp93NZVLhhVl0sHF1QM/7RSrDvRK7CGAZKq8COQ3/F2zLpMOPM
  PQIDAQAB
  -----END PUBLIC KEY-----
  </code></pre>
  
  <p>I need to be able to convert this into a format that I can insert into the ssh known_hosts file. For example:</p>
  
  <pre><code>localhost ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDj0HsJJ4I0p+gRYrpv3JFORk0NFB8YwlRdGBxja453pBzMBm6LyEmSqZAvv0UCguLI+Avo1HmDLJlrWd+1wVECRNSxD9twqcD5pkQcowy5hWOH0KbmBIdoYQqkm+nGhwSLSDJ5wO9k/F26D03d5/c0gNjB9UU9HrJ8zyB185vezxc6VM/kLlcoUMHT1aL/+cxbvlq5tkJDCmEQg05k4LgBWdfwUAXA1n3DlI9bU+CWb9hnmBUPFMHge56+Z1fhaJfvVW6VxLMh/W1NxK1Cxo4ig+0U0fYInqoMNcBT/6C7P2OdA8DbESCF5E7/9/eTLfsbW7EB7Ka3Mfyfm2a0Cswx
  </code></pre>
  
  <p>These two public keys should be the same, I think. They're just expressed in two different forms. (Right?) For the life of me, I can't figure out how to do this.</p>
  
  <p>So far, I'm loading a private key from a PEM file and parse it like so.  The PEMParser comes from bouncy castle:</p>
  
  <pre><code>FileReader keyPairReader = new FileReader(new File(applicationPropertiesService.getConfigDir(), KEY_PAIR_FILE));
  PEMParser parser = new PEMParser(keyPairReader);
  </code></pre>
  
  <p>I then get the public/private keypair from the parser.</p>
  
  <pre><code>PEMKeyPair pemKeyPair = (PEMKeyPair) parser.readObject();
  </code></pre>
  
  <p>From here I can get a SubjectPublicKeyInfo object and I can get my data and encode it to base64:</p>
  
  <pre><code>String pkBase64 = new BASE64Encoder().encode(publicKey.getEncoded())
  </code></pre>
  
  <p>This gives me the base64 string in the first public key above. But, for the life of me, I can't figure out how to get the ssh-rsa format.</p>
  
  <p>Any help would be appreciated.</p>
  
  <p>Thanks!</p>