Using Keys with JGit to Access a Git Repository Securely

You need to override the getJSch method in your custom factory class: class CustomConfigSessionFactory extends JschConfigSessionFactory { @Override protected JSch getJSch(final OpenSshConfig.Host hc, FS fs) throws JSchException { JSch jsch = super.getJSch(hc, fs); jsch.removeAllIdentity(); jsch.addIdentity( “/path/to/private/key” ); return jsch; } } Calling jsch.removeAllIdentity is important; it doesn’t seem to work without it. A caveat: I … Read more

Never ending of reading server response using jSch

The channel does not close itself when there is no input left. Try closing it yourself after you have read all data. while (true) { while (inputStream.available() > 0) { int i = inputStream.read(buffer, 0, 1024); if (i < 0) { break; } System.out.print(new String(buffer, 0, i));//It is printing the response to console } System.out.println(“done”); … Read more

SFTP file transfer using Java JSch

The most trivial way to upload a file over SFTP with JSch is: JSch jsch = new JSch(); Session session = jsch.getSession(user, host); session.setPassword(password); session.connect(); ChannelSftp sftpChannel = (ChannelSftp) session.openChannel(“sftp”); sftpChannel.connect(); sftpChannel.put(“C:/source/local/path/file.zip”, “/target/remote/path/file.zip”); Similarly for a download: sftpChannel.get(“/source/remote/path/file.zip”, “C:/target/local/path/file.zip”); You may need to deal with UnknownHostKey exception.

Public key authentication fails with JSch but work with OpenSSH with the same key

Your OpenSSH ssh connection is using rsa-sha2-512 key signature. While that does not prove that your server requires it, it’s quite probable that it does. JSch does not support rsa-sha2. And as JSch seems not to be updated anymore, it quite likely never will. There’s a fork of JSch that does though: https://github.com/mwiede/jsch At least … Read more