3

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-----"

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Emil Rojewski
  • 94
  • 1
  • 1
  • 5
  • 3
    You need to add the client's (new) public key to the `authorized_keys` file **ON THE SERVER** – dave_thompson_085 Jul 29 '15 at 18:46
  • So if i get it correctly I need to copy the key from id_rsa.pub and paste it in the .ssh/authorized_keys on the server ? – Emil Rojewski Jul 29 '15 at 21:17
  • copy&paste can work, as long as the result is one long line exactly as it is in the source file id_rsa.pub; depending on the terminals/UIs you use they might turn displayed line wraps into line breaks. A simple robust way is to `scp .ssh/id_rsa.pub user@host:.` then `ssh` to the server and `cat` the copy onto `authorized_keys` and check/fix the permissions (must be inaccessible to other users). Or if you don't yet have anything (needed) in server `authorized_keys` just chmod the local file and directly `scp -p .ssh/id_rsa.pub user@host:.ssh/authorized_keys`. – dave_thompson_085 Jul 30 '15 at 21:15
  • Yeah i used this method with scp and it all worked out :) so the problem was solved. Thanks for advice – Emil Rojewski Jul 31 '15 at 00:17
  • Here is the blog article explaining how to connect to remote host by using public key authentication from java: http://www.svlada.com/ssh-public-key-authentication/ – svlada Nov 23 '15 at 20:25
  • Related question: [Public key authentication fails with JSch but work with OpenSSH with the same key](https://stackoverflow.com/q/72743823/850848). – Martin Prikryl Dec 07 '22 at 07:54

2 Answers2

1

This how I connected localy using with Path of private Key when
privateKeyPath ="C:\Keys\private_key.ppk"

    public static OutputStream ConnectionUsingKey(String user, String hostName, String privateKeyPath)
        throws JSchException, IOException {
    JSch jsch = new JSch();
    Session session = null;
    try {

        jsch.addIdentity(privateKeyPath);
        session = jsch.getSession(user, hostName, 22);
        session.setConfig("PreferredAuthentications", "publickey");
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect();
        if (session.isConnected() == true) {
            System.out.println("Connection to Session server is successfully");
        }
        channel = session.openChannel("shell");
        channel.setInputStream(System.in);
        channel.setOutputStream(System.out);
        channel.connect(30 * 1000);
        return channel.getOutputStream();

    } catch (JSchException e) {
        throw new RuntimeException("Failed to create Jsch Session object.", e);
    }
}
Vladi
  • 1,662
  • 19
  • 30
0

Thank you @Vladi. In my case I needed to connect to a server that used both private key and a password. Hence I had to set the Config like this

        session.setConfig("PreferredAuthentications", "publickey,password");
        session.setPassword("some_password");
codester
  • 117
  • 2
  • 9