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