JSch: addIdentity from private key stored on hdfs

2019-02-20 03:57发布

问题:

This question already has an answer here:

  • JSch to add private key from a string 1 answer

I need to connect to an sftp server from an hadoop cluster. I would like to know if there is a way to load an identity from a private key stored in hdfs. Actually it seems that the JSch object accepts only a local path:

try {
    String privateKeyPath = "hdfs://namenode:8020/path/to/privatekey";  // need this one to be an hdfs path
    JSch jsch = new JSch();

    jsch.addIdentity(privateKeyPath);

    // [..]
}
catch (Exception ex) {
    // [..]
}

Any idea?

回答1:

Thanks to @Martin Prikryl answer, solved as following:

// Get sftp private/public key for JSch identity
FSDataInputStream fis = fs.open(privateKeyPath);
byte[] privateKeyBytes = IOUtils.toByteArray(fis);

fis = fs.open(publicKeyPath);
byte[] publicKeyBytes = IOUtils.toByteArray(fis);
fis.close();

JSch jsch = new JSch();
String idName = "ksftp";
byte[] passphrase = null;  
jsch.addIdentity(idName, privateKeyBytes, publicKeyBytes, passphrase);