5

我正在尝试使用NGit 连接到Github(即使用私钥和密码)。

有人可以带我过去吗?

我的正常获取是:

            var git = Git.CloneRepository()
            .SetDirectory(_properties.OutputPath)
            .SetURI(_properties.SourceUrlPath)
            .SetBranchesToClone(new Collection<string>() { "master" })
            .SetCredentialsProvider(new UsernamePasswordCredentialsProvider("username","password"))
            .SetTimeout(3600)
            .Call();

我将如何使用私钥执行此操作?

4

1 回答 1

4

经过长时间的战斗,许多谷歌搜索 Jgit 示例和更多痛苦,我找到了解决方案!

基本上你用你自己的覆盖和 SessionFactory 并在连接时注入你的证书:

public class CustomConfigSessionFactory : JschConfigSessionFactory
{
    public string PrivateKey { get; set; }
    public string PublicKey { get; set; }

    protected override void Configure(OpenSshConfig.Host hc, Session session)
    {
        var config = new Properties();
        config["StrictHostKeyChecking"] = "no";
        config["PreferredAuthentications"] = "publickey";
        session.SetConfig(config);

        var jsch = this.GetJSch(hc, FS.DETECTED);
        jsch.AddIdentity("KeyPair", Encoding.UTF8.GetBytes(PrivateKey), Encoding.UTF8.GetBytes(PublicKey), null);
    }
}

然后像这样注入它:

var customConfigSessionFactory = new CustomConfigSessionFactory();
customConfigSessionFactory.PrivateKey = properties.PrivateKey;
customConfigSessionFactory.PublicKey = properties.PublicKey;

NGit.Transport.JschConfigSessionFactory.SetInstance(customConfigSessionFactory);

var git = Git.CloneRepository()
          .SetDirectory(properties.OutputPath)
          .SetURI(properties.SourceUrlPath)
          .SetBranchesToClone(new Collection<string>() { "master" })
          .Call();
于 2013-03-17T07:11:19.813 回答