簡體   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