我正在使用netbeans 7.2运行JDK 1.7和Windows 7.我使用putty-keygen生成了SSH私钥和公钥对(SSH2-2048位).私钥没有任何密码.我现在正尝试使用SFTP连接到其中一台主机.但是当我传递私钥(ppk)来设置Identity时,代码返回无效的私钥错误.我在WinSCP中使用相同的私钥连接到同一主机,它工作正常.请帮我解决错误.这是我的代码:
JSch jsch = new JSch();
Session session = null;
try {
jsch.addIdentity("D:\\TEMP\\key.ppk");
session = jsch.getSession("tiabscp", "ssiw.support.qvalent.com", 22);
session.setConfig("StrictHostKeyChecking", "no");
//session.setPassword("");
session.connect();
Channel channel = session.openChannel("sftp");
System.out.println("Getting connected");
channel.connect();
System.out.println("connected successfully");
ChannelSftp sftpChannel = (ChannelSftp) channel;
sftpChannel.get("remotefile.txt", "localfile.txt");
sftpChannel.exit();
session.disconnect();
}catch (JSchException e) {
e.printStackTrace();
}catch (SftpException e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud) 我正在使用java.security.KeyPairGenerator来生成RSA密钥对,然后尝试通过Jsch(0.1.49)中提供的KeyPair类加载私钥.代码:
public static void main(String[] args) {
String header = "-----BEGIN RSA PRIVATE KEY-----";
String footer = "-----END RSA PRIVATE KEY-----";
KeyPairGenerator keyPairGenerator;
try {
keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048, new SecureRandom());
PrivateKey privateKey = keyPairGenerator.genKeyPair().getPrivate();
String key = new String(Base64.encodeBase64(privateKey.getEncoded()));
StringBuffer pem = new StringBuffer(header+"\n");
int len=key.length();
for( int idx=0 ; idx < len ; idx+= 64 )
pem.append(key.substring(idx, (idx+64)<len?(idx+64):len)+"\n");
pem.append(footer);
String privateKeyStr = pem.toString();
System.out.println(privateKeyStr);
com.jcraft.jsch.KeyPair.load(null, privateKeyStr.getBytes(), null);
} catch (JSchException e) {
// TODO Auto-generated catch block
e.printStackTrace(); …Run Code Online (Sandbox Code Playgroud)