AK4647
AK4647

Reputation: 1809

JSCH - Pass private key string instead of file path

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

Upvotes: 3

Views: 4371

Answers (2)

kknickkk
kknickkk

Reputation: 29

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

Upvotes: 0

Nikita Sapozhnikov
Nikita Sapozhnikov

Reputation: 324

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.

Upvotes: 2

Related Questions