I tried to generate the SSH key using the following code
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair keyPair=keyPairGenerator.generateKeyPair();
RSAPublicKey publicKey=(RSAPublicKey)keyPair.getPublic();
RSAPrivateKey privateKey=(RSAPrivateKey)keyPair.getPrivate();
String base64PubKey = Base64.encodeBase64String(publicKey.getEncoded());
ByteArrayOutputStream byteOs = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(byteOs);
dos.writeInt("ssh-rsa".getBytes().length);
dos.write("ssh-rsa".getBytes());
dos.writeInt(publicKey.getPublicExponent().toByteArray().length);
dos.write(publicKey.getPublicExponent().toByteArray());
dos.writeInt(publicKey.getModulus().toByteArray().length);
dos.write(publicKey.getModulus().toByteArray());
String publicKeyEncoded = new String(
Base64.encodeBase64(byteOs.toByteArray()));
String key = "ssh-rsa " + publicKeyEncoded + " ";
System.out.println("Public Key ------");
System.out.println(key);
System.out.println("------------------------------");
System.out.println("Private key");
System.out.println(Base64.encodeBase64(privateKey.getEncoded()));
Now, When I store the content of private key in a file and trying to validate it with putty it says invalid format of private key.
Could you guys help me out on this, some how I missing the private key format so putty is not recognizing it.
Putty is unable to recognize OpenSSH formatted keys -- they must first be converted into the Putty style using Puttygen.
There is a Debian/Ubuntu package for this conversion:
apt-get install putty-tools
puttygen openssh_formattted_key -o putty_formatted_key.ppk
You might be able to investigate this and figure out how the keys are converted, or run the command as a process from inside your code.
On Windows, the Puttygen GUI is available for this:
https://devops.profitbricks.com/tutorials/use-ssh-keys-with-putty-on-windows/
Download Link: https://the.earth.li/~sgtatham/putty/latest/x86/puttygen.exe
If you want to use this key generated directly, I would suggest you use something like MINGW32/MINGW64, Cygwin, etc. which allow you to use the ssh command in Command Prompt or some other terminal-like window.