1

我正在尝试使用 apache mina sshd 设置 ssh 服务器。我想使用公钥认证,基本上我想知道如何实现

package org.apache.sshd.server;
import java.security.PublicKey;
import org.apache.sshd.server.session.ServerSession;

public interface PublickeyAuthenticator {

boolean authenticate(String username, PublicKey key, ServerSession session);

}

我看到传递的是另一个公钥。所以我假设您应该将参数中给出的公钥与服务器拥有的公钥进行比较。但我不知道该怎么做。

我发现的一件事是这个实现。这似乎毫无意义,因为它似乎将公钥的模数与自身进行了比较。假设这个实现有一个错误,并且应该比较每个公钥的模数,这足以进行身份​​验证 - 模数同意吗?当然,如果我只是将我的公开可用公钥提供给这个函数,那么我会获得身份验证吗?

4

2 回答 2

8

我想我在源代码中找到了答案org.apache.sshd.server.auth.UserAuthPublicKey#auth。此类使用密钥进行实际身份验证。我认为让我感到困惑的是方法的名称 - authenticate()。实际情况如下:

  • 服务器请求客户端的公钥

  • 公钥被传递给PublickeyAuthenticator#authenticate

  • 您应该做的authenticate()就是检查这是您要允许的公钥

  • 如果authenticate()返回 true,UserAuthPublicKey#auth则将检查消息是否已使用私钥签名。如果是,则验证已验证。

于 2013-03-13T17:42:58.307 回答
1

下面的代码是如何使用 Apache MINA SSHD 执行公钥认证的示例,示例代码创建了一个 SFTP 服务器。

import java.io.File;
import java.io.IOException;
import java.util.Collections;

@Service
public class MySftpServer {

    private Log log = LogFactory.getLog(MySftpServer.class);

    @PostConstruct
    public void startServer() throws IOException {
        start();
    }

    private void start() throws IOException {
        SshServer sshd = SshServer.setUpDefaultServer();
        sshd.setHost("localhost");
        sshd.setPort(2222);
        sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(new File("host.ser")));
        sshd.setSubsystemFactories(Collections.singletonList(new SftpSubsystemFactory()));
        sshd.setPasswordAuthenticator((username, password, session) -> username.equals("test") && password.equals("password"));
        sshd.setPublickeyAuthenticator(new AuthorizedKeysAuthenticator(new File("<Location of authorized_keys file>")));
        sshd.start();
        log.info("SFTP server started");
    }
}

与@northshorefiend 在他的回答中提到的类似,在这种情况下AuthorizedKeysAuthenticator,将公钥传递给服务器并根据 authorized_keys 文件对其进行验证new AuthorizedKeysAuthenticator(new File("<Location of authorized_keys file>")。如果指定的公钥存在于文件中,则认证通过。

您可以在此处此处阅读有关此内容的更多详细信息

于 2019-09-03T16:49:48.547 回答