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 wrote the above in Scala, and then translated it over to Java, so it might not be quite right. The original Scala is as follows:

class CustomConfigSessionFactory extends JschConfigSessionFactory
{
    override protected def getJSch( hc : OpenSshConfig.Host, fs : FS ) : JSch =
    {
        val jsch = super.getJSch(hc, fs)
        jsch.removeAllIdentity()
        jsch.addIdentity( "/path/to/private/key" )
        jsch
    }
}

Leave a Comment