Java – unknownhostkey exception when accessing GitHub safely
I am using jgit to securely access the repository in GitHub I did the following to generate a secure communication key between GitHub and my client code
>Generate key pair:
ssh-keygen -t rsa
>Use account settings – > added public key to GitHub account SSH key – > Add SSH key > add the private key generated in step 1 to the local host:
ssh-add id_rsa
After this operation, when I try to access GitHub and clone, I still receive the following error:
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)
This is the code I use:
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();
}
Please tell me the problem here and what I can do to correct it
thank you.
Solution
This happens because ~ / ssh / kNown_ There is no GitHub entry in hosts, and the jsch used in jgit rejects the session by default For solutions, see this question: com jcraft. jsch. JSchException: UnknownHostKey
To set SSH session properties, you need to create a session factory for jgit:
SshSessionFactory.setInstance(new JschConfigSessionFactory() {
public void configure(Host hc,Session session) {
session.setConfig("StrictHostKeyChecking","no");
}
})
Or add stricthostkeychecking = no to ~ / ssh / config
