使用Mina SSHD(客户端)使用私钥连接SFTP

10

我试图连接到一个需要私钥认证的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);
    }
}

你有没有找到一种方法来做这件事? - Joao Pereira
我一直找不到与Mina相处的方法。 - Chuck Lowery
我也在寻找解决方案。 - Prakash Ramasamy
3个回答

0
根据ClientSession文档:
客户端会话是使用SshClient建立的。一旦会话创建成功,用户必须使用ClientAuthenticationManager.addPasswordIdentity(String)ClientAuthenticationManager.addPublicKeyIdentity(java.security.KeyPair)进行身份验证,然后调用auth()方法。
所以你可能需要尝试类似这样的操作:
// path to your private key
Path privateKeyPath = Paths.get("/path/to/your/privatekey.pem");
        
// load the private key
FileKeyPairProvider fileKeyPairProvider = new FileKeyPairProvider(privateKeyPath);
Iterable<KeyPair> keyPairs = fileKeyPairProvider.loadKeys();

try (SshClient client = SshClient.setUpDefaultClient()) {
    client.start();

    try (ClientSession session = client.connect("username", "hostname", 22).verify().getSession()) {
        // authenticate using the private key
        session.addPublicKeyIdentity(keyPairs.iterator().next());

        // auth agent can be null
        session.auth().verify();

        ...
    }
} ...

-1
我找到了一个集成测试的例子,希望这能帮到你。

https://github.com/apache/mina-sshd/blob/master/sshd-core/src/test/java/org/apache/sshd/client/auth/pubkey/RSAVariantsAuthPublicKeyTest.java#L87

@BeforeClass
public static void setupClientAndServer() throws Exception {
    sshd = CoreTestSupportUtils.setupTestServer(RSAVariantsAuthPublicKeyTest.class);
    sshd.setSignatureFactories(RSA_FACTORIES);
    sshd.setKeyPairProvider(KEYS_PROVIDER);
    sshd.setPasswordAuthenticator(RejectAllPasswordAuthenticator.INSTANCE);
    sshd.setHostBasedAuthenticator(RejectAllHostBasedAuthenticator.INSTANCE);
    sshd.setPublickeyAuthenticator((username, key, session) -> {
        String keyType = KeyUtils.getKeyType(key);
        outputDebugMessage("authenticate(%s) keyType=%s session=%s", username, keyType, session);
        return KeyPairProvider.SSH_RSA.equals(keyType);
    });

    sshd.start();
    port = sshd.getPort();

    client = CoreTestSupportUtils.setupTestClient(RSAVariantsAuthPublicKeyTest.class);
    client.setServerKeyVerifier((session, peerAddress, key) -> {
        String keyType = KeyUtils.getKeyType(key);
        outputDebugMessage("verifyServerKey - keyType=%s session=%s", keyType, session);
        return KeyPairProvider.SSH_RSA.equals(keyType);
    });
    client.start();
}

-1

Mina SSHD 支持授权密钥身份验证。

客户端设置示例

    KeyPairResourceLoader loader = SecurityUtils.getKeyPairResourceParser();
    Collection<KeyPair> keys = loader.loadKeyPairs(null, filePath, passwordProvider);

    // provide keys to client session
    try (ClientSession session = ...estblish initial session...) {
        for (KeyPair kp : keys) {
            session.addKeyIdentity(kp);
        }
        
        session.auth().await(...);
    }

请查看客户端设置

更完整的客户端设置示例可在此处找到。


嗨@zaxishere,您的解决方案正在引用服务器而不是客户端。问题涉及客户端。 - Chuck Lowery
我编辑了答案,提供了关于客户端设置的更多细节。 - zaxishere

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接