gpt4 book ai didi

java - 如何在 Java 中读取 RSA key ?

转载 作者:行者123 更新时间:2023-11-30 05:51:29 28 4
gpt4 key购买 nike

我正在尝试用 Java 读取 RSA 公钥和私钥文件。

我的 RSA 公钥和私钥是使用 PuttyGen 生成的。 (SSH-2 RSA,1024 位)

我用来读取文件的代码是:

//public key
pubkeyBytes = getBytesFromFile(new File(pubKeyfileName));
KeySpec pubSpec = new X509EncodedKeySpec(pubkeyBytes);
RSAPublicKey pubKey =(RSAPublicKey) rsakeyFactory.generatePublic(pubSpec);

//private key
privkeyBytes = getBytesFromFile(new File(privKeyfileName));
PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privkeyBytes);
PrivateKey privKey = rsakeyFactory.generatePrivate(privSpec);

它抛出:

java.security.InvalidKeyException: invalid key format
at sun.security.x509.X509Key.decode(Unknown Source)

最佳答案

Putty 使用自己的 key 格式。您需要将 Putty key 导出为 OpenSSH 格式 - 请参阅 How to convert SSH keypairs generated using PuttyGen(Windows) into key-pairs used by ssh-agent and KeyChain(Linux) .

然后,您需要将 OpenSSH key 转换为 pkcs8 格式 - 参见 How to Load RSA Private Key From File . Cygwin 版本的 openssh 就可以很好地工作;无需寻找 Unix 系统来运行 openssh

关于java - 如何在 Java 中读取 RSA key ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12663084/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com