Lakshmi
Lakshmi

Reputation: 2294

JSCH - Invalid private key -working in actual server

We are trying to use JSCH to download the file from a remote server. The SFTP key exchange is already set up between the two servers when we try

SFP username@hostname

it connects successfully without asking for any password. But in java code when we try connecting using JSCH getting invalid private key exception.

ERROR com.crer.log.debug - com.jcraft.jsch.JSchException: invalid privatekey:

the code I have done is something like below

JSch jsch = new JSch();
            String privateKey = location of the private key on client server
            jsch.addIdentity(privateKey);
            session = jsch.getSession(stpUser, sftpHost, sftpPort);
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();

Edit:

The JSCH version im using is 0.1.54

The private key begins like

---- BEGIN SSH2 ENCRYPTED PRIVATE KEY ----
Subject: username
Comment: "2048-bit rsa, username@host, Tue Dec 13 2016 19:25:22 \
-0500"

I even tried converting the private key to openssh format but getting some exception

ssh-keygen -i -f id_rsa_2048_a > id_rsa_2048_a_openssh
Private key -f is unreadable: Failed to open `-f': No such file or directory / Failed to read file `-f'.
Error: Cannot determine the type of the key.

if i remove the -f from the command it works but I believe the file is not properly converted as if i use that file i get the same exception.

Any help here will be very helpful . Not sure whats going wrong.

Upvotes: 0

Views: 2048

Answers (1)

John Siu
John Siu

Reputation: 5092

I recently encountered this in Jenkins ssh plugin which also use JSCH.

JSCH only accept the old PEM format private key. It can be generate as follow:

ssh-keygen -m PEM -t rsa

The -m PEM instruct ssh-keygen to output in PEM format which can be accepted by JCSH.

Upvotes: 1

Related Questions