Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSCH - Invalid private key

Tags:

java

jsch

I am running JDK 1.7 & Windows 7 using netbeans 7.2 I have generated a SSH private & public key pair (SSH2-2048 bits) using putty-keygen. I do not have any password for private key. I am now trying to connect to one of the host machine using SFTP. But when I pass private key (ppk) to set Identity, code is returning invalid private key error. I used same private key in WinSCP to connect to same host & it is working fine. Kindly help me to resolve the error. Here is my code:

JSch jsch = new JSch();

Session session = null;

try {

    jsch.addIdentity("D:\\TEMP\\key.ppk");

    session = jsch.getSession("tiabscp", "ssiw.support.qvalent.com", 22);
    session.setConfig("StrictHostKeyChecking", "no");
    //session.setPassword("");
    session.connect();
    Channel channel = session.openChannel("sftp");
    System.out.println("Getting connected");
    channel.connect();
    System.out.println("connected successfully");
    ChannelSftp sftpChannel = (ChannelSftp) channel;
    sftpChannel.get("remotefile.txt", "localfile.txt");
    sftpChannel.exit();
    session.disconnect();
}catch (JSchException e) {

    e.printStackTrace();

}catch (SftpException e) {

    e.printStackTrace();
}
like image 914
Virgo_The_Perfectionist Avatar asked Mar 11 '13 06:03

Virgo_The_Perfectionist


People also ask

What is JSch addIdentity?

addIdentity(String prvkey, String pubkey, byte[] passphrase) Adds an identity to be used for public-key authentication. protected void. addSession(Session session) Adds a session to our session pool.

What is setKnownHosts in JSch?

public class JSch extends Object. This class serves as a central configuration point, and as a factory for Session objects configured with these settings. Use getSession to start a new Session. Use one of the addIdentity methods for public-key authentication. Use setKnownHosts to enable checking of host keys.


2 Answers

I guess that your key is not in OpenSSH key file format. JSch expects the private key to be in OpenSSH format.

You can use PuTTYgen to convert your private key to work with OpenSSH by following the steps described here:

  1. Press Load and select the Private Key that was created with PuTTYgen.
  2. Enter the passphrase to load the key.
  3. From the Conversions menu select export OpenSSH key
  4. Save the private key.
like image 167
rgerganov Avatar answered Oct 14 '22 20:10

rgerganov


Perhaps not a solution for you, but I found this question when I searched for my issue.

I had accidentally given the path to the public keyfile when JSCH expected the private keyfile.

like image 23
jontejj Avatar answered Oct 14 '22 18:10

jontejj