I'm using below code to connect remote server and I followed below steps to connect private/public key generation & concatenate of public key with authorized key.


private Session createSession() throws JSchException {
        JSch jsch = new JSch();
            jsch.addIdentity(privateKey);                   //add private key path as ~/.ssh/id_rsa
            Session session;
            session = jsch.getSession(user, host, port);
            java.util.Properties config = new java.util.Properties();

        Properties cfg = new Properties();
            cfg.put("trust", "true");
            cfg.put("StrictHostKeyChecking", "no");
            cfg.put("HashKnownHosts", "yes");

            return session;


1. I can able to generate private/public key in the path ~/.ssh/id_rsa(private key) and ~/.ssh/id_rsa.pub(public key)
    >> ssh-keygen (or) ssh-keygen -t rsa -b 4096
   Note: Generated key with no passphrase
2. I have added public key with authorized_keys with below command
    >> ssh user@host "echo \"`cat ~/.ssh/id_rsa.pub`\" >> .ssh/authorized_keys"

Still I'm facing the exception "com.jcraft.jsch.JSchException: Auth fail". Please guide me to proceed.


I believe this can happen for several reasons:

  • The private key is password protected, which you have already verified is not the case.

  • The directory containing the keys is encrypted.

  • The file permissions on the .ssh directory and or public/private keys are too open. They should be:

    • ssh directory: 700
    • public key: 644
    • private key: 600 (possibly even 400)
  • What also might be going on is the format of the public key within the authorized keys file is incompatible. You might need to convert it to a different format. Assuming OpenSSH:

    • Convert to SSH2: ssh-keygen -i -f /path/to/private/key ssh-keygen -i -f /path/to/public/key
    • Convert from SSH2: ssh-keygen -e -f /path/to/private/key ssh-keygen -e -f /path/to/public/key
  • I had Jsch successfully authenticate once. Then I re-did keygen and udpated keys everywhere and now I'm getting the error above too Feb 9 '18 at 18:18
  • Changing private key from 600 to 400 fixed it for me.
    – Peter Hull
    Oct 11 '20 at 9:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.