【问题标题】:sftp with public key is not working带有公钥的 sftp 不起作用
【发布时间】:2017-08-04 22:30:04
【问题描述】:

使用 ssh-keygen 生成 RSA 公钥。

尝试使用通过sftp连接远程服务器:

 JSch jsch = new JSch();
        try {

            String publicKey = "/home/testuser/.ssh/id_rsa.pub";
            jsch.addIdentity(publicKey);
            session = jsch.getSession(sftpUsername, sftpHostname, sftpPort);
            session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
        } catch (JSchException e) {
            logger.error("Unable to obtain session", e);
        }

出现以下错误:

com.jcraft.jsch.JSchException: invalid privatekey: /home/testuser/.ssh/id_rsa.pub
        at com.jcraft.jsch.IdentityFile.<init>(IdentityFile.java:261)
        at com.jcraft.jsch.IdentityFile.newInstance(IdentityFile.java:135)
        at com.jcraft.jsch.IdentityFile.newInstance(IdentityFile.java:130)
        at com.jcraft.jsch.JSch.addIdentity(JSch.java:206)
        at com.jcraft.jsch.JSch.addIdentity(JSch.java:192)

有什么建议吗?

【问题讨论】:

    标签: java sftp jsch public-key


    【解决方案1】:

    你有:

    jsch.addIdentity(publicKey);
    

    JSch javadoc 说:

    public void addIdentity(String prvkey) throws JSchException;

    添加用于公钥认证的身份。在将其注册到 identityRepository 之前,将使用密码对其进行解密。

    参数:

    • prvkey - 私钥文件的文件名。这也用作密钥的标识名称。假设对应的公钥位于同名文件中,后缀为 .pub。

    当 JSch 需要私钥时,您已经提供了公钥。

    如果你仔细想想,这是有道理的。公钥没有什么秘密。 JSch 想要一个秘密,所以它可以证明你是谁。

    您的私钥可能在~/.ssh/id_rsa 中(没有.pub 扩展名)。

    您可能需要使用addIdentity 的两参数版本,以便提供密码来解密私钥。

    【讨论】:

      猜你喜欢
      • 2019-06-30
      • 2017-01-28
      • 2023-02-15
      • 1970-01-01
      • 2021-07-19
      • 1970-01-01
      • 2017-01-03
      • 1970-01-01
      • 2011-06-17
      相关资源
      最近更新 更多