Using Keys with JGit to Access a Git Repository Securely

后端 未结 3 1327
無奈伤痛
無奈伤痛 2020-12-05 07:54

I\'m using JGit to access a remote Git repo, and I need to use SSH for it. JGit uses JSch to provide secure access. However, I\'m not sure how to set the key file and the kn

相关标签:
3条回答
  • 2020-12-05 08:29

    Jsch sesems to not like a known_hosts file in the hashed format-- it must conform to the format produced by:

    ssh-keyscan -t rsa hostname >> ~/.ssh/known_hosts

    e.g.

    <hostname> ssh-rsa <longstring/longstring>
    

    not:

     |1|<hashed hostname>= ecdsa-sha2-nistp256 <hashed fingerprint>=
    
    0 讨论(0)
  • 2020-12-05 08:37

    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
        }
    }
    
    0 讨论(0)
  • 2020-12-05 08:53

    Managed to find the issue. The public key in the server side had a different name other than the usual id_rsa.pub, while the private key on my side was id_rsa. JSch expects by default the public key to have the same name as the private key plus the .pub suffix. Using a key pair with a common name (ex.: private = key_1 and public = key_1.pub) solves the issue.

    0 讨论(0)
提交回复
热议问题