1

I have the contents of the key pair file for SFTP as a string. I need to use JSch to add the contents, but addIdentity only accepts a file path. Is there anyway I can do this? The public key is already uploaded to the host. I tested the connection through WinSCP using the private key, and it was successful. When I try to connect from the Java process I get the

[2021-01-12 11:00:41,518] [ERROR] [jobLauncherTaskExecutor-1] [c.j.p.d.u.FileUtil] [] : Exception : 
com.jcraft.jsch.JSchException: USERAUTH fail
    at com.jcraft.jsch.UserAuthPublicKey.start(UserAuthPublicKey.java:119)

Below is code snippet:

Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
String privateKeyPath = "-----BEGIN RSA PRIVATE KEY-----\n" +
        "Proc-Type: 4,ENCRYPTED\n" +
        "hkjhbkkhbkbkhbkjhbkjbkjhbkjb\n" +
        "-----END RSA PRIVATE KEY-----\n";
String passphrase = "passphrase";
JSch jsch = new JSch();
try (FileInputStream fileInputStream = new FileInputStream(new File(fileName));){
    jsch.addIdentity(sftpHost, privateKeyPath.getBytes(), null, passphrase.getBytes());
    session = jsch.getSession(sftpUser, sftpHost, sftpPort);
    java.util.Properties config = new java.util.Properties();
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);
    session.connect();
    log.info("Host connected.");
    channel = session.openChannel("sftp");
    channel.connect();
    log.info("sftp channel opened and connected.");
    channelSftp = (ChannelSftp) channel;
    channelSftp.cd(sftpWorkingFolder);
    channelSftp.put(fileInputStream, new File(fileName).getName());
} catch (JSchException | SftpException | IOException e) {
    log.error("Exception : ", e);
}
Andulos
  • 433
  • 6
  • 20
  • _"addIdentity only accepts a file path"_ -- Why do you think this is true? You can provide the private key in binary form. – Jim Garrison Jan 12 '21 at 22:33
  • When I run the process on my local machine, I pass the file path to addIDentity(filePath) method, and it worked fine. On the tomcat server, I have to look for alternate ways to use the private key. – Andulos Jan 12 '21 at 22:36
  • I don't think you want to hardcode the private key into your code. If you care at all about security, you'll provide the private key file at deployment time (i.e. not as part of the .war file) and link to its location via a system property. And, you'll have a secure method for providing the passphrase, which also won't be part of the .war. – Jim Garrison Jan 12 '21 at 22:46

0 Answers0