I'm trying to connect to localhost using SSH with key. But I still get an error:
Auth Failed
Here is the method implementation:
public void downloadUsingPublicKey(String username, String host)
{
String privateKey = "~/.ssh/id_rsa";
JSch jsch = new JSch();
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
try
{
jsch.addIdentity(privateKey);
System.out.println("Private Key Added.");
session = jsch.getSession(username, host);
System.out.println("session created.");
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
channel = session.openChannel("sftp");
channel.connect(); System.out.println("shell channel connected....");
channelSftp = (ChannelSftp)channel;
channelSftp.cd(Config.dir);
System.out.println("Changed the directory...");
} catch (JSchException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SftpException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}finally
{
if(channelSftp!=null)
{
channelSftp.disconnect();
channelSftp.exit();
}
if(channel!=null) channel.disconnect();
if(session!=null) session.disconnect();
}
}
I've created my public/private key pair using Linux terminal, as follows:
ssh-keygen -t rsa -b 4096 -C "myemail@email.com"
I didn't put any phrase.
Next step:
ssh-add ~/.ssh/id_rsa
And finally
cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
Then when I run my program I get error:
com.jcraft.jsch.JSchException: Auth fail
at com.jcraft.jsch.Session.connect(Session.java:512)
at com.jcraft.jsch.Session.connect(Session.java:183)
at pl.eroj.filedownloader.Downloader.downloadUsingPublicKey(Downloader.java:73)
at pl.eroj.filedownloader.Downloader.main(Downloader.java:107)
Any ideas? My key is of OpenSSH type starting with line "-----BEGIN RSA PRIVATE KEY-----"