Skip to content

Instantly share code, notes, and snippets.

@MorbosVermin
Last active August 29, 2015 14:05
Show Gist options
  • Save MorbosVermin/660fda489b64befefa8d to your computer and use it in GitHub Desktop.
Save MorbosVermin/660fda489b64befefa8d to your computer and use it in GitHub Desktop.
/**
* Converts the given RSAPublicKey obejct to RSA-SSH format byte array. This
* byte[] returned DOES NOT include the prefixed <i>ssh-rsa</i> nor any appended
* text (i.e. the username or email address) for a comment.
*
* @param pubkey java.security.interfaces.RSAPublicKey to convert.
* @return byte[]
* @throws IOException
*/
public static final byte[] publicKeyToRsaSsh(RSAPublicKey pubkey)
throws IOException {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
write(new String("ssh-rsa").getBytes("UTF-8"), buf);
write(pubkey.getPublicExponent().toByteArray(), buf);
write(pubkey.getModulus().toByteArray(), buf);
return buf.toByteArray();
}
private static final void write(byte[] b, OutputStream o)
throws IOException {
for(int i = 24; i >= 0; i -= 8)
o.write((b.length >>> i) & 0xFF);
o.write(b);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment