安全访问GitHub时出现UnknownHostKey异常

Izz*_*zza 8 java ssl github jgit

我正在使用jgit安全地访问GitHub中的存储库.我做了以下操作来生成GitHub和我的客户端代码之间的安全通信密钥.

  1. 生成密钥对:

    ssh-keygen -t rsa
    
    Run Code Online (Sandbox Code Playgroud)
  2. 使用帐户设置 - > SSH密钥 - >添加SSH密钥,将公钥添加到GitHub帐户

  3. 将步骤1中生成的私钥添加到本地主机:

    ssh-add id_rsa
    
    Run Code Online (Sandbox Code Playgroud)

执行此操作后,当我尝试访问GitHub并进行克隆时,我仍然会收到以下错误:

org.eclipse.jgit.api.errors.TransportException: git@github.com:test/test_repo.git: UnknownHostKey: github.com. RSA key fingerprint is 16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48
at org.eclipse.jgit.api.FetchCommand.call(FetchCommand.java:137)
at org.eclipse.jgit.api.CloneCommand.fetch(CloneCommand.java:178)
at org.eclipse.jgit.api.CloneCommand.call(CloneCommand.java:125)
Run Code Online (Sandbox Code Playgroud)

这是我使用的代码:

    String localPath, remotePath;
    Repository localRepo;
    Git git;

    localPath = <path_to_local_repository>;
    remotePath = "git@github.com:test/test_repo.git";

    try {
        localRepo = new FileRepository(localPath + "/.git");
    } catch (IOException e) {
        e.printStackTrace();
    }
    git = new Git(localRepo);

    CloneCommand cloneCmd =  git.cloneRepository().
                setURI(remotePath).
                setDirectory(new File(localPath));
        try {
            cloneCmd.call();
        } catch (GitAPIException e) {
            log.error("git clone operation failed");
            e.printStackTrace();
        }
Run Code Online (Sandbox Code Playgroud)

请告诉我这里的问题,我该怎么做才能纠正它.

谢谢.

Den*_*kiy 18

之所以会发生这种情况,是因为你没有github的入口~/.ssh/known_hosts,并且JSch在jgit默认情况下用于拒绝会话.请参阅此问题以获得解决方案:com.jcraft.jsch.JSchException:UnknownHostKey

要设置ssh会话属性,需要为jgit创建会话工厂:

SshSessionFactory.setInstance(new JschConfigSessionFactory() {
  public void configure(Host hc, Session session) {
    session.setConfig("StrictHostKeyChecking", "no");
  }
})
Run Code Online (Sandbox Code Playgroud)

或添加StrictHostKeyChecking=no~/.ssh/config

  • 我确实有一个条目,但仍然遇到相同的错误,我使用StrictHostKeyChecking = no作为解决方法,但不想让我的代码容易受到攻击。有什么想法吗? (2认同)