I’m looking for a way to programmatically create ssh compatible id_rsa and id_rsa.pub files in Java.
I got as far as creating the KeyPair:
KeyPairGenerator generator;
generator = KeyPairGenerator.getInstance("RSA");
// or: generator = KeyPairGenerator.getInstance("DSA");
generator.initialize(2048);
keyPair = generator.genKeyPair();
I can’t figure out however how to create the String representation of the PrivateKey and PublicKey in the KeyPair.
The key format used by ssh is defined in the RFC #4253. The format for RSA public key is the following :
All data type encoding is defined in the section #5 of RFC #4251. string and mpint (multiple precision integer) types are encoded this way :
for instance, the encoding of the string “ssh-rsa” is:
To encode the public :
To have a string représentation of the key just encode the returned byte array in Base64.
For the private key encoding there is two cases:
getEncodedonRSAPrivateKey.