我正在尝试用 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 使用自己的密钥格式。您需要将 Putty 密钥导出为 OpenSSH 格式 - 请参阅如何将使用 PuttyGen(Windows) 生成的 SSH 密钥对转换为 ssh-agent 和 KeyChain(Linux) 使用的密钥对 https://stackoverflow.com/questions/2224066/how-to-convert-ssh-keypairs-generated-using-puttygenwindows-into-key-pairs-use.
然后,您需要将 OpenSSH 密钥转换为 pkcs8 格式 - 请参阅如何从文件加载 RSA 私钥 https://stackoverflow.com/questions/3243018/how-to-load-rsa-private-key-from-file。 Cygwin 版本的 openssh 可以很好地完成此任务;无需寻找Unix系统来运行openssh
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)