I am trying to get private Key from a .keystore File that I created.
So far, this is working:
try {
FileInputStream is = new FileInputStream("C:\\Program Files\\Java\\...mykeystore.keystore");
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(is, "mypassword".toCharArray());
Key privKey = keystore.getKey("alias", "mypassword".toCharArray());
StringWriter stringWriter = new StringWriter();
JcaPEMWriter pemWriter = new JcaPEMWriter(stringWriter);
pemWriter.writeObject(privKey);
pemWriter.close();
System.out.println(stringWriter);
For the System.out.println(stringWriter) I get the following output:
-----BEGIN RSA PRIVATE KEY-----
PRIVATE KEY IS HERE
-----END RSA PRIVATE KEY-----
I now would like to use this private key to create a ssh connection to a Unix Server. On the unix server side I already put the public key in to the authorized_key files.
For the ssh connection I use JSch. According to JSCH - Invalid private key I now need to convert this key to PEM Format. I did this with the example from Abdelhameed Mahmoud:
StringWriter stringWriter = new StringWriter();
JcaPEMWriter pemWriter = new JcaPEMWriter(stringWriter);
pemWriter.writeObject(privKey);
pemWriter.close();
System.out.println(stringWriter);
byte[] privateKeyPEM = stringWriter.toString().getBytes();
And here it is where I am stuck.
How can I use the privateKeyPEM byte object? I want to use this with the jsch.addIdentity()
But I do not really understand how I can use this byte[] privateKeyPEM variable to set the identity?
Here an Example for my JSch part:
JSch jsch = new JSch();
jsch.addIdentity(**What to put here??**);
session = jsch.getSession(user, getIP(), getPort());
session.setConfig("PreferredAuthentications", "publickey");
//session.setPassword(pwd);
session.setConfig("StrictHostKeyChecking", "no");
session.connect(3000);
Has anyone experience with this?
Sorry for the missing comments, as I am still figuring out how to get this working I did not add any comments yet.
Thanks in advance for any helpful input.
Cheers Armin
Is nothing about this in the jsch documentation?
The parameters are:
JSch.addIdentity(String name, byte[] prvkey, byte[] pubkey, byte[] passphrase)
In your case (unencrypted PEM):
jsch.addIdentity(user, privateKeyPEM, null, null);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With