关于ssl:如何从RSA Privatekey.pem文件中获取java.security.PrivateKey对象?

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

有一个私人的RSA密钥文件(ockey.pem)。我用Java from this to get the key的私人文件。using the key is generated this below OpenSSL命令行。注释:on this change anything我OpenSSL命令行的下面。P></

1
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

如何看样below the认证。P></

///////////////////////////////////////////////////////////
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----- //////////////////////////////////////////////////////////////

就是我跟随P></

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

但要P></

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

Please help。P></


确保privatekey为der格式,并且您使用的是正确的keyspec。我相信你应该在这里使用pkcs8作为privkeybytes

首先,需要将私钥转换为二进制DER格式。下面介绍如何使用openssl:

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

最后,

1
2
3
4
5
6
7
8
9
10
11
12
13
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);
    }