-->

How can I read RSA keys in Java?

2019-03-01 05:24发布

问题:

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.