import com.jcraft.jsch.*;
import com.jcraft.jsch.JSchException;
import oracle.jdbc.driver.OracleDriver;
import java.io.*;
import java.util.*;
import java.sql.*;
import java.net.*;
public class SecureFTP {
public static void main(String[] args) throws IOException , ClassNotFoundException, JSchException, SftpException{
JSch jsch = new JSch();
File file = new File("/home/xxxxx/.ssh/id_rsa");
Session session = null;
URL keyFileURL = null;
URI keyFileURI = null;
if (file.exists())
{
keyFileURL = file.toURL();
if (keyFileURL == null)
{
System.out.println("what");
throw new RuntimeException("Key file not found in classpath");
}
}
else System.out.println("FIle not found");
try{
keyFileURI = keyFileURL.toURI();
}
catch(Exception URISyntaxException)
{
System.out.println("Wrong URL");
}
String privateKey = ".ssh/id_rsa";
//jsch.addIdentity(privateKey);
jsch.addIdentity(new File(keyFileURI).getAbsolutePath());
System.out.println(new File(keyFileURI).getAbsolutePath() + " LOL");
session = jsch.getSession("username", "servername");
//session.setPassword("password");
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
// connect
session.connect();
// get SFTP channel
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp schannel = (ChannelSftp) channel;
FileInputStream fis = new FileInputStream(sourcefile);
schannel.put(fis, destinationfile );
fis.close();
}
schannel.exit();
session.disconnect();
}
}
正如您从我注释掉的代码中看到的,我已经尝试了一切可能的方法来使其正常工作,唯一有效的是直接设置密码。我尝试使用生成的 RSA 私钥,但始终出现身份验证失败。
我已将公钥添加到目标服务器上的授权 key 列表中。并且没有密码。
还有什么我应该做的吗?就像说,在生成 key 时?我缺少一个步骤吗?
我可以使用另一个库来实现相同的功能吗?
最佳答案
确保必要的文件存在(客户端上有 id_rsa 和 id_rsa.pub,服务器上有authorized_keys)。确保您可以使用这些文件通过其他工具(例如 ssh
)使用公钥身份验证。
如果看起来没问题,则问题可能出在您的 Java 安全提供程序上。如果您认为您拥有正确的文件,请继续阅读。
RSA 私钥存储有不同的格式,而 SSH 使用的是非标准格式。大多数提供商都期望使用称为 CRT RSA key 的东西,当 JSch 没有向他们提供该格式的 key 时,他们会引发异常,JSch 会默默地处理该异常并继续执行下一个身份验证方法。
您的提供商是什么?以下代码片段将帮助您找到答案:
import java.security.KeyFactory;
…
KeyFactory f = KeyFactory.getInstance("RSA");
System.out.println(f.getProvider().getName());
<小时/>
更新:我做了一些检查,从 Java 5 开始,SunPKCS11 提供程序在 Solaris 系统上以最高优先级安装,以提高性能。由于我不运行 Solaris,因此无法测试它,但我相信这可能是导致问题的原因。
JSch 不允许您通过其 API 指定用于此操作的提供程序,因此您必须更改已安装提供程序的优先级。事实上,我建议尝试从该应用程序中删除 SunPKCS11;当您的应用程序启动时运行此代码一次:
Security.removeProvider("SunPKCS11-Solaris");
关于java - 在java中使用私钥身份验证来保护FTP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8389099/