在C#中以编程方式将证书和私钥转换为.PFX

Mar*_*cus 11 c# security ssl-certificate pfx lets-encrypt

我有一个成功的LetsEncrypt证书请求的.cer文件输出.

我有原始私钥用于为LetsEncrypt创建证书签名请求(CSR).

现在我们需要使用.NET以编程方式将这两个文件组合成一个用于IIS的PFX包

由于我们试图以编程方式执行此操作,因此pvk2pfx不实用,如果可能,我们希望避免使用openssl.

为了演示,我们尝试复制此功能但使用CS .NET而不是pvk2pfx:pvk2pfx.exe -pvk Server.pvk -spc Server.cer -pfx Server.pfx

我已经详尽地进行了研究,以下是我看到的可能性:

一种方法似乎是使用X509Certificate2,如:

// Import the certificate
X509Certificate2 cert = new X509Certificate2("c:\\cert.cer");

// Import the private key
X509Certificate2 cert = new X509Certificate2("c:\\key.pvk");

// Or import the private key - Alternative method
X509DecryptString(token, @"c:\CA.pvk", "mypassword");

// Export the PFX file
certificate.Export(X509ContentType.Pfx, "YourPassword");
File.WriteAllBytes(@"C:\YourCert.pfx", certificateData);
Run Code Online (Sandbox Code Playgroud)

这里有一些其他的方法,但所有这些方法似乎省略了关于私钥的部分或他们需要pvk2pfx.exe

从证书文件转换为pfx文件 /sf/answers/335817471/

如何以编程方式创建X509Certificate2? http://www.wiktorzychla.com/2012/12/how-to-create-x509certificate2.html

选择,创建和查找X509证书:http: //www.wou.edu/~rvitolo06/WATK/Demos/HPCImageRendering/code/ImageRendering/AppConfigure/CertHelper.cs

无法将带有私钥的生成证书导出到字节数组 无法将带有私钥的生成证书导出到.net 4.0/4.5中的字节数组

如何以编程方式将带有证书链的pfx导入证书存储区. /sf/answers/640698691/

以C#编程方式导入.cer和.pvk证书文件,以便与https://gist.github.com/BrandonLWhite/235fa12247f6dc827051一起使用netsh http add sslcert

将cer转换为pfx证书的方法 https://gist.github.com/domgreen/988684

任何帮助非常感谢:-)


编辑1

CryptoGuy建议我们需要这个链接:https://gist.github.com/BrandonLWhite/235fa12247f6dc827051

这是否意味着这样的事情会很好?

CSP部件是否必要?

谢谢!

using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography;

    var PublicKey = AssemblyUtility.GetEmbeddedFileAsByteArray("Cert.cer");
    var PrivateKey = AssemblyUtility.GetEmbeddedFileAsByteArray("PrivateKey.pvk");
    var certificate = new X509Certificate2(PublicKey, string.Empty, 
        X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
    var cspParams = new CspParameters
    {
        ProviderType = 1,
        Flags = CspProviderFlags.UseMachineKeyStore,
        KeyContainerName = Guid.NewGuid().ToString().ToUpperInvariant()
    };
    var rsa = new RSACryptoServiceProvider(cspParams);

    rsa.ImportCspBlob(ExtractPrivateKeyBlobFromPvk(PrivateKey));
    rsa.PersistKeyInCsp = true;
    certificate.PrivateKey = rsa;

    certificate.Export(X509ContentType.Pfx, "YourPassword");
    File.WriteAllBytes(@"C:\YourCert.pfx", certificateData);
Run Code Online (Sandbox Code Playgroud)

Mar*_*cus 1

CryptoGuy 的回答非常有帮助,为我们指明了正确的方向。

我们仍在努力导入二进制 DER 文件,但此代码解决了这个问题:

var oc = OpenSSL.X509.X509Certificate.FromDER(bio); 
Run Code Online (Sandbox Code Playgroud)

这些页面很有用:

https://github.com/openssl-net/openssl-net/blob/master/ManagedOpenSsl/X509/X509Certificate.cs

https://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509certificate2.rawdata

感谢你的帮助 :)