使用充气城堡阅读SSLeay格式私钥

时间:2021-10-02 18:24:15

InvalidKeyException is throw while trying to read SSLeay Format private key.

尝试读取SSLeay格式的私钥时抛出InvalidKeyException。

Please find below the details:- I have a SSLeay Format private key.The pem format begins with the below file

请在下面找到详细信息: - 我有一个SSLeay格式的私钥.pem格式从下面的文件开始

-----BEGIN RSA PRIVATE KEY-----

-----开始RSA私钥-----

I am writing the code to get the private key saved in a byte format and convert the same to PrivateKey. Variable privateKeyBytes contains the private key in byte format/

我正在编写代码以获取以字节格式保存的私钥并将其转换为PrivateKey。变量privateKeyBytes包含字节格式的私钥/

String pkStrFormat = new String(privateKeyBytes, "UTF-8");
pkStrFormat = pkStrFormat.replaceAll("(-----BEGIN RSA PRIVATE KEY-----\\r?\\n|-----END RSA PRIVATE KEY-----+\\r?\\n?)","");
byte[] keyBytesOfPrivateKey = org.bouncycastle.util.encoders.Base64
                    .decode(pkStrFormat.getBytes());
KeyFactory ecKeyFac = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytesOfPrivateKey);            
PrivateKey priKey = ecKeyFac.generatePrivate(keySpec);

I am getting the below exception:-

我得到以下例外: -

Caused by: java.security.InvalidKeyException: IOException : version mismatch: (supported:     00, parsed:     01
    at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:350)
    at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:356)

The code works fine when PKCS8 Format keys are used.

使用PKCS8格式密钥时,代码工作正常。

1 个解决方案

#1


1  

PEM files starting with BEGIN RSA PRIVATE KEY are PKCS#1, not PKCS#8. PKCS#1 is essentially PKCS#8 for fixed algorithm RSA and therefore with algorithm identifier removed. Either convert your key like in https://superuser.com/questions/606215/openssl-pkcs8-default-format-gives-rsa-private-key:

以BEGIN RSA PRIVATE KEY开头的PEM文件是PKCS#1,而不是PKCS#8。对于固定算法RSA,PKCS#1本质上是PKCS#8,因此删除了算法标识符。要么像https://superuser.com/questions/606215/openssl-pkcs8-default-format-gives-rsa-private-key那样转换你的密钥:

openssl pkcs8 -topk8 -inform pem -in file.key -outform pem -nocrypt -out file.pem

or use PEMParser similar to Bouncy Castle : PEMReader => PEMParser (without the password stuff)

或使用类似于Bouncy Castle的PEMParser:PEMReader => PEMParser(没有密码的东西)

#1


1  

PEM files starting with BEGIN RSA PRIVATE KEY are PKCS#1, not PKCS#8. PKCS#1 is essentially PKCS#8 for fixed algorithm RSA and therefore with algorithm identifier removed. Either convert your key like in https://superuser.com/questions/606215/openssl-pkcs8-default-format-gives-rsa-private-key:

以BEGIN RSA PRIVATE KEY开头的PEM文件是PKCS#1,而不是PKCS#8。对于固定算法RSA,PKCS#1本质上是PKCS#8,因此删除了算法标识符。要么像https://superuser.com/questions/606215/openssl-pkcs8-default-format-gives-rsa-private-key那样转换你的密钥:

openssl pkcs8 -topk8 -inform pem -in file.key -outform pem -nocrypt -out file.pem

or use PEMParser similar to Bouncy Castle : PEMReader => PEMParser (without the password stuff)

或使用类似于Bouncy Castle的PEMParser:PEMReader => PEMParser(没有密码的东西)