如何在Java中读取RSA密钥? [英] How can I read RSA keys in Java?
问题描述
我尝试读取Java中的RSA公钥和私钥文件。
I am trying to read the RSA public and private keys files in Java.
我的RSA公钥和私钥是使用PuttyGen生成的。 (SSH-2 RSA,1024位)
My RSA public and private key is generated using PuttyGen. (SSH-2 RSA, 1024 bits)
我用于读取文件的代码是:
The code I am using for reading file is:
//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)使用的密钥对。
Putty uses its own key format. You need to export the Putty key to the OpenSSH format - see How to convert SSH keypairs generated using PuttyGen(Windows) into key-pairs used by ssh-agent and KeyChain(Linux).
然后,您需要将OpenSSH键转换为pkcs8格式 - 请参阅如何从文件加载RSA私钥。 Cygwin版本的openssh将正常工作;没有必要找到一个Unix系统来运行 openssh
。
Then, you need to convert the OpenSSH key to pkcs8 format - see How to Load RSA Private Key From File. The Cygwin version of openssh will work just fine for this; there's no need to find a Unix system to run openssh
.
这篇关于如何在Java中读取RSA密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!