本文介绍了如何从RSA Privatekey.pem文件中获取java.security.PrivateKey对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我有一个RSA私钥文件(OCkey.pem)。使用java我必须从这个文件中获取私钥。使用下面的openssl命令生成此密钥。
注意:我无法在下面的openssl命令中更改任何内容。

  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 

证书如下所示。

以下是我的尝试

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

但是获得

请帮助。

解决方案

确保私钥是DER格式,并且您正在使用正确的keyspec。我相信你应该在这里使用PKCS8作为privkeybytes



首先,你需要将私钥转换为二进制DER格式。
下面是如何使用来实现的:

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

最后,

  public static PrivateKey getPrivateKey(String filename抛出异常{

文件f =新文件(文件名);
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);
返回kf.generatePrivate(spec);
}


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.

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

Please help.

解决方案

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

这篇关于如何从RSA Privatekey.pem文件中获取java.security.PrivateKey对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-08 21:21