Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using private RSA Key from .keystore File with Jsch

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

like image 763
ArBei Avatar asked Feb 14 '17 14:02

ArBei


Video Answer


1 Answers

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);
like image 138
Omikron Avatar answered Oct 13 '22 02:10

Omikron