首页 文章

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

提问于
浏览
9

我有一个成功的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 certficate
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);

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

从cert文件转换为pfx文件https://stackoverflow.com/a/4797392/3693688

如何以编程方式创建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

无法将带有私钥的生成证书导出到字节数组Cannot export generated certificate with private key to byte array in .net 4.0/4.5

如何以编程方式将带有证书链的pfx导入证书存储区 . https://stackoverflow.com/a/9152838/3693688

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

将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);

1 回答

相关问题