首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在Java中将私钥作为字符串传递,以便使用SSHJ通过SFTP进行连接?

如何在Java中将私钥作为字符串传递,以便使用SSHJ通过SFTP进行连接?
EN

Stack Overflow用户
提问于 2022-03-12 01:53:38
回答 1查看 575关注 0票数 1

下面的代码通过SFTP连接,使用密钥的目录路径来加载它。

下面是当前的代码(为了以防万一,我已经指定了库)

代码语言:javascript
运行
复制
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.userauth.keyprovider.KeyProvider;
import net.schmizz.sshj.transport.verification.PromiscuousVerifier;

SSHClient sftp = new SSHClient();
KeyProvider privateKey = sftp.loadKeys("/home/sample/.ssh/id_rsa");
sftp.addHostKeyVerifier(new PromiscuousVerifier());
sftp.connect("111.222.333.444");
sftp.authPublickey("sample", privateKey);

是否有一种方法可以将私钥的内容作为字符串传递而不是使用其目录路径?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-12 06:21:32

是的,您可以调用库的折叠方法来支持用例。

代码语言:javascript
运行
复制
/**
 * Creates a {@link KeyProvider} instance from passed strings. Currently only PKCS8 format private key files are
 * supported (OpenSSH uses this format).
 * <p/>
 *
 * @param privateKey     the private key as a string
 * @param publicKey      the public key as a string if it's not included with the private key
 * @param passwordFinder the {@link PasswordFinder} that can supply the passphrase for decryption (may be {@code
 *                       null} in case keyfile is not encrypted)
 *
 * @return the key provider ready for use in authentication
 *
 * @throws SSHException if there was no suitable key provider available for the file format; typically because
 *                      BouncyCastle is not in the classpath
 * @throws IOException  if the key file format is not known, etc.
 */   
public KeyProvider loadKeys(String privateKey, String publicKey, PasswordFinder passwordFinder) throws IOException

如果在您使用的库版本中没有这种功能,那么可以考虑升级它。

代码语言:javascript
运行
复制
<dependency>
    <groupId>net.schmizz</groupId>
    <artifactId>sshj</artifactId>
    <version>0.10.0</version>
</dependency>
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71446402

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档