我试图连接到一个需要私钥认证的SFTP服务器,并希望使用Mina来实现。查阅文档,我发现如何使用密码认证进行身份验证,但没有关于如何使用私钥认证的示例代码。我没有找到任何可以演示如何使用Mina进行私钥认证的示例代码。
请问这个库是否支持私钥认证?如果支持,能否提供一个加载密钥和建立连接的示例代码呢?
这是一个使用SSHTools的示例,供参考。
private static void authenticate(Ssh2Client ssh2, String host, Integer port, String username, InputStream privateKey) {
Ssh2PublicKeyAuthentication auth = createKeyAuthentication(privateKey);
try {
int result = ssh2.authenticate(auth);
if (result != SshAuthentication.COMPLETE) {
throw new AuthenticationIncomplete(host, port, username, result);
}
} catch (SshException ex) {
throw new UnableToAuthenticate(host, port, username, ex);
}
}
private static Ssh2PublicKeyAuthentication createKeyAuthentication(InputStream privateKey) {
try {
SshPrivateKeyFile privateKeyFile = SshPrivateKeyFileFactory.parse(StreamUtil.readIntoByteArray(privateKey));
SshKeyPair keyPair = privateKeyFile.toKeyPair("");
Ssh2PublicKeyAuthentication auth = new Ssh2PublicKeyAuthentication();
auth.setPrivateKey(keyPair.getPrivateKey());
auth.setPublicKey(keyPair.getPublicKey());
return auth;
} catch (IOException | InvalidPassphraseException ex) {
throw new ConfigurationIssue(ex);
}
}