Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
620 views
in Technique[技术] by (71.8m points)

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

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 change anything on this openssl command below.

openssl> req -newkey rsa:1024 -sha1 -keyout OCkey.pem -out OCreq.pem -subj "/C=country/L=city/O=OC/OU=myLab/CN=OCserverName/" -config req.conf

The certificate looks like below.

///////////////////////////////////////////////////////////
bash-3.00$ less OCkey.pem
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,EA1DBF8D142621BF

BYyZuqyqq9+L0UT8UxwkDHX7P7YxpKugTXE8NCLQWhdS3EksMsv4xNQsZSVrJxE3
Ft9veWuk+PlFVQG2utZlWxTYsUVIJg4KF7EgCbyPbN1cyjsi9FMfmlPXQyCJ72rd
...
...
cBlG80PT4t27h01gcCFRCBGHxiidh5LAATkApZMSfe6BBv4hYjkCmg==
-----END RSA PRIVATE KEY-----
//////////////////////////////////////////////////////////////

Following is what I tried

byte[] privKeyBytes = new byte[(int)new File("C:/OCkey.pem").length()]; 
PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(privKeyBytes));

but getting

"java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format"

Please help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...