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);

2 Answers 2

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);
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?

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.