2

How do I pass my private key (content not file) to JSCH (for sftp)?

AK4647
  • 1,371
  • 1
  • 10
  • 11
  • [Why is "Is it possible to..." a poorly worded question?](https://softwareengineering.meta.stackexchange.com/questions/7273/why-is-is-it-possible-to-a-poorly-worded-question/7274) – azurefrog Apr 10 '17 at 15:52

2 Answers2

2

Instead of using KeyPair.load(JSch jsch,String prvfile,String pubfile) you can use overloaded method KeyPair.load(JSch jsch,byte[] prvkey, byte[] pubkey). It should support loading content directly. Source: apidoc.

0

I have been struggling with the same problem but I've found a solution you have to add the carriage return characters in the string containing the private key and the conver it to US_ASCII:

private static byte[] readKey(String keyFileContent){

    keyFileContent = keyFileContent.replace("-----BEGIN RSA PRIVATE KEY-----", "-----BEGIN RSA PRIVATE KEY-----\r\n").replace("-----END RSA PRIVATE KEY-----", "\r\n-----END RSA PRIVATE KEY-----");
    return keyFileContent.getBytes(StandardCharsets.US_ASCII);

}

Then you can call the addIdentity function in this way:

 jsch.addIdentity("myconnection", readKey(privateKeyString), null, null);

Then you can follow the example on the documentation: Documentation

kknickkk
  • 29
  • 4
  • You do not have to add anything. The key in the correct format contains the new lines. If you have to add them, it's only because you have removed them earlier. – Martin Prikryl Jul 06 '19 at 11:41
  • I had this problem reading files with Android, I believe it depends on how you read the file, maybe the best thing is to use a regex to check whether the carriage return and new line are present and add them if necessary – kknickkk Jul 06 '19 at 12:24
  • Maybe then you should add a complete code, including the reading part. Otherwise your answer makes little sense. – Martin Prikryl Jul 06 '19 at 12:25