0

I'm fairly new to Android development and am trying to use Jsch using a private key to access a remote server. I have placed the private key in res/raw folder but am struggling on how to access the file path of the private key when trying to authenticate. I have previously got this working for a Java project. Here is a copy of what I have so far.

    private Session sshConnect() throws JSchException, IOException
{
    try
    {
        //Login details
        jschSession = jsch.getSession(sshUsername, sshServer, 22);

        //Connect using private key and corresponding passphrase
        jsch.addIdentity("./res/raw/id_rsa", passphrase);

        //Ignore SSH key warnings
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        jschSession.setConfig(config);

        //System.out.println(localPort);
        jschSession.connect();
        return jschSession;
    }
    catch (Exception ex)
    {
        throw new RuntimeException("SSH connection failed: " + ex.getMessage(), ex);
    }
}

This then throws the following error when I try to run

   java.lang.RuntimeException: SSH connection failed: java.io.FileNotFoundException: ./res/raw/id_rsa: open failed: ENOENT (No such file or directory)

I've tried the following to try and access the contents of the res folder, with no such luck:

   jsch.addIdentity("file:///android_res/raw/id_rsa", passphrase);
user3424480
  • 362
  • 2
  • 6
  • 19

2 Answers2

2

Simply, you can get the file from raw folder.

  InputStream privateKeyByteStream = getResources()
            .openRawResource(
               getResources().getIdentifier("private_key_without_extension", "raw", getPackageName()));

Then add identity

jSch.addIdentity("anyIdentityName", privateKeyBytes, publicKeyBytes, passphrase);
huseyin
  • 1,367
  • 16
  • 19
0

I'm not sure there's a way to access the raw resource as a file.

You may need to save the resource to a temporary path and refer to that in addIdentity.

For accessing the resource see for example:
Android how to get access to raw resources that i put in res folder?

Community
  • 1
  • 1
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992