Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SSH Private Key validation using Java [duplicate]

Tags:

java

ssh

jsch

My user would need to validate his Private Key against his Git Repository . It is similar to "Test Connection" button in any DB Client tool.

I am using JSCH to do this validation in Java (i just need to connect using SSH and tell that connection is successful). Below is my Java code

public class SSHConnect {


    private String file = "c:\\me\\ssh-keys\\config_31_jan";

    public static void main(String... args) {
         new SSHConnect().invoke();
    }

    public void invoke () {
        JSch jSch = new JSch();
        try {
            jSch.addIdentity(file);
            Session session = jSch.getSession("MY_USER_NAME","github.my_company.com",22) ;

            session.connect();
        } catch (JSchException e) {
            e.printStackTrace();
        }
    }
}

I get the below exception while doing so

com.jcraft.jsch.JSchException: UnknownHostKey: github.***.com. RSA key fingerprint is 6e:23:f4:4a:49:fd:18:77:ce:35:3e:ae:7c:a9:f6:ed
    at com.jcraft.jsch.Session.checkHost(Session.java:805)
    at com.jcraft.jsch.Session.connect(Session.java:345)
    at com.jcraft.jsch.Session.connect(Session.java:183)
    at com.pcfdev.main.SSHConnect.invoke(SSHConnect.java:23)
    at com.pcfdev.main.SSHConnect.main(SSHConnect.java:13)

Am i missing to do anything ? Please help

like image 713
Arun Avatar asked Mar 11 '26 22:03

Arun


1 Answers

You are not loading the key through the addIdentity method. You are effectively setting the private key as "c:\\me\\ssh-keys\\config_31_jan"

You need to load the content of your file first. For example :

private String filePath = "c:\\me\\ssh-keys\\config_31_jan";

public void invoke () {
    File f = new File (filePath );
    String key = new String(Files.readAllBytes(f.toPath())); 

    JSch jSch = new JSch();
    try {
        jSch.addIdentity(key);
        Session session = jSch.getSession("MY_USER_NAME","github.my_company.com",22) ;

        session.connect();
    } catch (JSchException e) {
        e.printStackTrace();
    }
}
like image 200
Laurent B Avatar answered Mar 13 '26 13:03

Laurent B