【问题标题】:how do I create a pfx compatible with X509Certificate2 with openssl如何使用 openssl 创建与 X509Certificate2 兼容的 pfx
【发布时间】:2018-10-06 07:29:01
【问题描述】:

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

我设法生成的 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()

【问题讨论】:

    标签: c# .net openssl


    【解决方案1】:

    堆栈跟踪告诉我一切。

    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 实例中,可用于加密和解密。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-13
      • 1970-01-01
      • 2013-12-24
      • 2014-07-09
      • 1970-01-01
      • 1970-01-01
      • 2016-08-10
      • 1970-01-01
      相关资源
      最近更新 更多