繁体   English   中英

如何使用 openssl 创建与 X509Certificate2 兼容的 pfx

[英]how do I create a pfx compatible with X509Certificate2 with openssl

我正在尝试使用 OpenSSL 创建一个可以与System.Security.Cryptography.X509Certificates.X509Certificate2使用的 RSA 密钥对。

我设法生成的 PFX 给了我这个堆栈跟踪

创建一个未加密的私钥(我意识到这不是最佳实践)

openssl genrsa -out private.pem 2048

从私钥创建公钥

openssl rsa -in private.pem -outform PEM -pubout -out public.pem

从私钥创建证书文件

openssl req -x509 -key private.pem -out cert.pem -days 365 -nodes -subj "/C=US/ST=Colorado/L=Colorado Springs/O=Contoso/OU=Security/CN=mypurpose.contoso.org"

使用自签名证书创建 pfx 文件

openssl pkcs12 -in cert.pem -inkey private.pem -export -out combined.pfx

提示输入密码以保护 pkcs

尝试实例化X509Certificate2的实例

new X509Certificate2(@"C:\\path\\to\\combined.pfx", "password", X509KeyStorageFlags.Exportable);

   at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
   at System.Security.Cryptography.X509Certificates.X509Utils._LoadCertFromFile(String fileName, IntPtr password, UInt32 dwFlags, Boolean persistKeySet, SafeCertContextHandle& pCertCtx)
   at System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromFile(String fileName, Object password, X509KeyStorageFlags keyStorageFlags)
   at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(String fileName, String password, X509KeyStorageFlags keyStorageFlags)
   at Program.Main()

堆栈跟踪告诉我一切。

at System.Security.Cryptography.X509Certificates.X509Utils._LoadCertFromFile(String fileName, IntPtr password, UInt32 dwFlags, Boolean persistKeySet, SafeCertContextHandle& pCertCtx)
at System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromFile(String fileName, Object password, X509KeyStorageFlags keyStorageFlags)

这意味着我的 PFX 文件中没有 CERTIFICATE,因为我在openssl pkcs12命令中使用了-nocerts

在密码学中,PKCS #12 定义了一种存档文件格式,用于将许多密码学对象存储为单个文件。 它通常用于将私钥与其 X.509 证书捆绑在一起或捆绑信任链的所有成员。 PKCS 12

一个 pkcs12 文件真的想包含除了私钥/公钥之外的其他东西,它需要一个 X.509 证书; 即:

  • 证书版本
  • 序列号
  • 签名算法
  • 发行人
  • 有效性不是以前
  • 有效期不在此后。

这是按照我想要的方式工作的最终命令:

openssl pkcs12 -in cert.pem -inkey private.pem -export -clcerts -out combined.pfx -passout pass:

这允许我使用此代码实例化:

new X509Certificate2(@"C:\\path\\to\\combined.pfx", (string)null, X509KeyStorageFlags.Exportable);

我正在使用一些额外的代码来加载由openssl genrsaopenssl rsa生成的 private.pem 和 public.pem: https : //stackoverflow.com/a/32243171/26877 此代码将原始 PEM 数据(仅私钥/公钥)加载到RSACryptoServiceProvider实例中,该实例可用于加密和解密。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM