How to get the java.security.PrivateKey object from RSA Privatekey.pem file?

前端 未结 1 696
滥情空心
滥情空心 2020-12-10 04:46

I have a RSA private key file (OCkey.pem). Using java i have to get the private key from this file. this key is generated using the below openssl command. Note : I can\'t c

相关标签:
1条回答
  • 2020-12-10 05:46

    Make sure the privatekey is in DER format and you're using the correct keyspec. I believe you should be using PKCS8 here for the privkeybytes

    Firstly, you need to convert the private key to binary DER format. Heres how you would do it using OpenSSL:

    openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key.pem -out private_key.der -nocrypt
    

    Finally,

    public static PrivateKey getPrivateKey(String filename) throws Exception {
    
            File f = new File(filename);
            FileInputStream fis = new FileInputStream(f);
            DataInputStream dis = new DataInputStream(fis);
            byte[] keyBytes = new byte[(int) f.length()];
            dis.readFully(keyBytes);
            dis.close();
    
            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory kf = KeyFactory.getInstance("RSA");
            return kf.generatePrivate(spec);
        }
    
    0 讨论(0)
提交回复
热议问题