Home > Mobile >  Unable to authorise using jsch private key
Unable to authorise using jsch private key

Time:03-09

I am trying to connect to a local ssh for testing purposes.

I am trying to login using ssh keys with jsch.

This is what I am putting in config:

config.put(STRICT_HOST_KEY_CHECK, strictHostKeyCheckValue); // no
config.put("PreferredAuthentications", "publickey");

The keys are valid and I am passing in the correct path to them.

The sever is running in background. But I am not able to connect to it. The error is “Auth failed”. Can anyone suggest where should I look further.

I am working on macos.

Added the code:

String privateKey = "/Users/username/.ssh/id_rsa";
String publicKey = "/Users/username/.ssh/id_rsa.pub";

public InputStream read(String objectName, ProxyHTTP proxyHTTP) throws IOException {
    Session session = null;
    Channel channel = null;
    ChannelSftp channelSftp = null;

    try {
        JSch jsch = new JSch();
        session = jsch.getSession(username, domain, sftpPort);
    
        if (proxyHTTP != null) {
            session.setProxy(proxyHTTP);
        }

        if (privateKey != null) {
            InputStream input = new FileInputStream(privateKey);
            byte[] privateKeyBytes = new byte[input.available()];
            input.read(privateKeyBytes);
            input.close();

            input = new FileInputStream(publicKey);
            byte[] publicKeyBytes = new byte[input.available()];
            input.read(publicKeyBytes);
            input.close();
            jsch.addIdentity(username,privateKeyBytes,publicKeyBytes,null);
        } else {
            throw new RuntimeException("Private Key Cannot be null.");
        }

        Properties config = new Properties();
        config.put(STRICT_HOST_KEY_CHECK, strictHostKeyCheckValue); // no for testing
        config.put("PreferredAuthentications", "publickey");
        // trust any unkown host.
        config.put("trust", "true");

        session.setConfig(config);

        session.connect();

        if (session.isConnected()) {
            channel = session.openChannel("sftp");
            channel.connect();

            if (channel.isConnected()) {
                ....
            }
        }
    } catch (Exception e) {
        ....
    } finally {
        if (channelSftp != null && channelSftp.isConnected()) channelSftp.disconnect();
        if (channel != null && channel.isConnected()) channel.disconnect();
        if (session != null && session.isConnected()) session.disconnect();
    }

    return null;
}

CodePudding user response:

I've never used ssh where the client and server are the same host, but I just tried. The server STILL uses ~/.ssh/authorized_keys to look for the public key. IS it there? Make sure with cat ~/.ssh/id_rsa.pub >>~/.ssh/authorized_keys. That at least is what my public key file is. Yours might be different.

  • Related