How can I read RSA keys in Java?

孤街醉人 提交于 2019-12-02 01:45:57

问题


I am trying to read the RSA public and private keys files in Java.

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);

It throws:

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

回答1:


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).

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.



来源:https://stackoverflow.com/questions/12663084/how-can-i-read-rsa-keys-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!