将PEM传统私钥转换为PKCS8私钥

问题描述 投票:0回答:4

我已获得一个带有证书和公钥/私钥的 PEM 文件。具体来说,它包括标题

-----BEGIN CERTIFICATE-----   
-----END CERTIFICATE-----   
-----BEGIN RSA PRIVATE KEY-----   
-----END RSA PRIVATE KEY-----   
-----BEGIN RSA PUBLIC KEY-----   
-----END RSA PUBLIC KEY-----

按照特定顺序。

我的理解是,在

BEGIN RSA PRIVATE KEY
标头后面没有标头,该 pem 文件包含传统格式 (PKCS1) 的私钥,未加密。

我需要将此私钥转换为 DER 编码的 PKCS8 未加密格式,以便与 java 服务器代码一起使用,特别是 PKCS8EncodedKeySpec。我尝试过使用 rsa 和 pkcs8 命令的 OpenSSL,但没有成功。如果有更简单的东西,没有特定需要使用 openssl。

具体:

openssl rsa -in IServer_Key.orig.prikey.pem -out IServer_Key.pkcs8.pem
openssl rsa -in IServer_Key.orig.prikey.pem -out IServer_Key.pkcs8.pem -pubin openssl pkcs8 -in IServer_Key.orig.prikey.pem -out IServer_Key.pkcs8.pem -nocrypt

我也尝试过指定 inform 和 outform 但没有成功。

user@ubuntu:~/TestCerts$ openssl rsa -in IServer_Key.pem -out IServer_Key.pkcs8.pem -pubin 
unable to load Public Key 
5925:error:0906D06C:PEM routines:PEM_read_bio:no start line:pem_lib.c:650:
Expecting: PUBLIC KEY

user@ubuntu:~/TestCerts$ openssl rsa -in IServer_Key.orig.prikey.pem -out IServer_Key.pkcs8.pem 
unable to load Private Key 
5993:error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag:tasn_dec.c:1316: 
5993:error:0D06C03A:asn1 encoding routines:ASN1_D2I_EX_PRIMITIVE:nested asn1 error:tasn_dec.c:828:
5993:error:0D08303A:asn1 encoding routines:ASN1_TEMPLATE_NOEXP_D2I:nested asn1 error:tasn_dec.c:748:Field=n, Type=RSA 
5993:error:0D09A00D:asn1 encoding routines:d2i_PrivateKey:ASN1 lib:d2i_pr.c:99: 
5993:error:0907B00D:PEM routines:PEM_READ_BIO_PRIVATEKEY:ASN1 lib:pem_pkey.c:125:

user@ubuntu:~/TestCerts$ openssl pkcs8 -in IServer_Key.orig.prikey.pem -out IServer_Key.pkcs8.pem -nocrypt 
Error decrypting key 
6022:error:0906D06C:PEM routines:PEM_read_bio:no start line:pem_lib.c:650:
Expecting: PRIVATE KEY

此时任何帮助将不胜感激。

openssl certificate
4个回答
113
投票

尝试使用以下命令。我还没有尝试过,但我认为它应该有效。

openssl pkcs8 -topk8 -inform PEM -outform DER -in filename -out filename -nocrypt

86
投票

使用 openssl 将私钥从 PKCS#1 转换为 PKCS#8:

# openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in pkcs1.key -out pkcs8.key

只要您拥有 PEM(文本格式)中的 PKCS#1 密钥,如问题中所述,就可以使用。


0
投票

我知道这是一篇旧文章,但我有相同的要求(即从 PKCS#1 转换为 PKCS#8),所以我首先来到这里。

经过一番研究,我找到了答案这里,我认为值得分享。
在这篇文章中,tytk也提到了这个对 PKCS#1 与 PKCS#8 的很好的描述

话虽如此,总结一下:

  1. 使用
    openssl genrsa
    时,生成的私钥默认为 PKCS#1 格式。
  2. 要转换为 PKCS#8,只需运行命令
    openssl pkey
    ,如下所示:
    openssl pkey -in IServer_Key.orig.prikey.pem -out IServer_Key.pkcs8.pem

-3
投票

创建新证书:

openssl req -newkey rsa:2048 -x509 -keyout key.pem -out cert.pem -sha256 -days 365

生成解码证书:

openssl pkcs8 -in key.pem -out key_unencrypted.pem
© www.soinside.com 2019 - 2024. All rights reserved.