如何使用 OpenSSL 从 .cer 中提取 RSA public 密钥并将其存储在 .pem 中?

How to extract the RSA public key from a .cer and store it in a .pem using OpenSSL?

我需要从 *.cer 文件中提取 public 密钥 (RSA)。我希望提取密钥并将其存储在 .pem 文件中,这样我就可以使用它的值来使用 jsencrypt.

加密值

以下命令将 .cer 转换为 .pem

openssl x509 -inform der -in certificate.cer -out certificate.pem

然而它并没有生成一个带有 public 键的文件,而是一个包含 *.cer 文件内容的文件。

-----BEGIN CERTIFICATE-----
MIICPDCCAamgAwIBAg............
*lots of extra contents*
-----END CERTIFICATE-----

我应该使用什么命令来提取 public 密钥并将其存储在 .pem 文件中?

使用此命令,我能够使用 public 密钥的内容生成 .pem

openssl x509 -inform der -in certificate.cer -pubkey -noout > certificate_publickey.pem

产生:

-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCsM+whXrxmbCkPfkwY2EehYpIp
*blah blah blah blah*
-----END PUBLIC KEY-----

PowerShell 解决方案:

$certFile = "[path to .cer file]"
$cer = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($certFile)
$cer.PublicKey.Key.ToXmlString($false)

来自 C# 的解决方案:

string certificate = @"<PATH TO .CER>"; 
X509Certificate2 cert = new X509Certificate2(certificate); 
string xml = cert.GetRSAPublicKey().ToXmlString(false);