JSch – invalid privatekey exception
This Java example tries to use JSch to transfer a file from the local folder to a remote server using public and private keys, instead of a password.
pom.xml
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
SFTPFileTransfer.java
package com.mkyong.io.howto;
import com.jcraft.jsch.*;
public class SFTPFileTransfer {
private static final String REMOTE_HOST = "1.1.1.1";
private static final String USERNAME = "";
private static final int REMOTE_PORT = 22;
public static void main(String[] args) {
String localFile = "/home/mkyong/Test.java";
String remoteFile = "/home/mkyong/test/Test2.java";
Session jschSession = null;
try {
JSch jsch = new JSch();
jsch.setKnownHosts("/home/mkyong/.ssh/known_hosts");
jschSession = jsch.getSession(USERNAME, REMOTE_HOST, REMOTE_PORT);
// private key location
jsch.addIdentity("/home/mkyong/.ssh/id_rsa");
jschSession.connect(10000);
Channel sftp = jschSession.openChannel("sftp");
sftp.connect(5000);
ChannelSftp channelSftp = (ChannelSftp) sftp;
// transfer file from local to remote server
channelSftp.put(localFile, remoteFile);
channelSftp.exit();
} catch (JSchException | SftpException e) {
e.printStackTrace();
} finally {
if (jschSession != null) {
jschSession.disconnect();
}
}
System.out.println("Done");
}
}
But it throws the invalid privatekey
exception.
Terminal
com.jcraft.jsch.JSchException: invalid privatekey: [B@1324409e
at com.jcraft.jsch.KeyPair.load(KeyPair.java:664)
at com.jcraft.jsch.KeyPair.load(KeyPair.java:561)
at com.jcraft.jsch.IdentityFile.newInstance(IdentityFile.java:40)
at com.jcraft.jsch.JSch.addIdentity(JSch.java:406)
at com.jcraft.jsch.JSch.addIdentity(JSch.java:366)
at com.mkyong.io.howto.SFTPFileTransfer.main(SFTPFileTransfer.java:31)
1. cat /home/mkyong/.ssh/id_rsa
Check the private key, and it looks something like:
Terminal
$ cat /home/mkyong/.ssh/id_rsa
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC...
...
...
...MAECAwQF
-----END OPENSSH PRIVATE KEY-----
2. Solution
The Jsch seems not to support the above private key format, to solve it, we can use ssh-keygen
to convert the private key format to the RSA
or pem
mode, and the above program works again.
Terminal
$ ssh-keygen -p -f ~/.ssh/id_rsa -m pem
Recheck the private key content, it should starts with BEGIN RSA
.
Terminal
$ cat /home/mkyong/.ssh/id_rsa
-----BEGIN RSA PRIVATE KEY-----
MIIG4wIBAAK...
...
...
...E428GBDI4
-----END RSA PRIVATE KEY-----
Thanks it worked!
Doesn’t work
Thankyou
Thank you so much.. It saved my day <3
dependency solves