Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Certificate and Private Key to .PFX programmatically in C#

I have a .cer file output from a successful LetsEncrypt certificate request.

I have the original Private Key used to create the Certificate Signing Request (CSR) for LetsEncrypt.

Now we need to programmatically combine these two files into a PFX bundle for IIS using .NET

Since we are trying to to do this programmatically pvk2pfx is not practical, and we would like to avoid openssl if possible.

To demonstrate though, we are trying to replicate this function but using CS .NET instead of pvk2pfx: pvk2pfx.exe -pvk Server.pvk -spc Server.cer -pfx Server.pfx

I have researched exhaustively and here are the possibilities I see:

One method seems to be using X509Certificate2 something like:

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

Here are some other methods but all of them seem to omit the part about the Private Key or they require pvk2pfx.exe

Conversion from cert file to pfx file https://stackoverflow.com/a/4797392/3693688

How to create a X509Certificate2 programmatically? http://www.wiktorzychla.com/2012/12/how-to-create-x509certificate2.html

Select, Create and Find X509 Certificates: http://www.wou.edu/~rvitolo06/WATK/Demos/HPCImageRendering/code/ImageRendering/AppConfigure/CertHelper.cs

Cannot export generated certificate with private key to byte array Cannot export generated certificate with a private key to byte array in .NET 4.0/4.5

How to programmatically import a pfx with a chain of certificates into the certificate store. https://stackoverflow.com/a/9152838/3693688

Import .cer and .pvk certificate files programmatically in C# for use with netsh http add sslcert https://gist.github.com/BrandonLWhite/235fa12247f6dc827051

Method to convert cer to pfx cert https://gist.github.com/domgreen/988684


EDIT 1

CryptoGuy suggested we need this link: https://gist.github.com/BrandonLWhite/235fa12247f6dc827051

Does that mean something like this would be good?

Are the CSP parts necessary?

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);
like image 905
Marcus Avatar asked Feb 15 '16 17:02

Marcus


People also ask

How do I create a .PFX file from a certificate and a private key?

Run the DigiCert® Certificate Utility for Windows (double-click DigiCertUtil). In the Certificate Export wizard, select Yes, export the private key, select pfx file, and then check Include all certificates in the certification path if possible, and finally, click Next. A . pfx file uses the same format as a .

How do I create a .PFX file from certificate and private key online?

With that you can generate the pfx file by the following steps: Import private key in the "Private Keys" tab; Import the certificate in the "Certificates" tab; Generate the pfx file by selecting the certificate and then "Export", select PKCS #12 as the format.


1 Answers

CryptoGuy's answer was really helpful and pointed us in the right direction.

We were still struggling to import a Binary DER file but this code fixed that:

var oc = OpenSSL.X509.X509Certificate.FromDER(bio); 

These pages were useful:

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

Thanks all for your help :)

like image 164
Marcus Avatar answered Sep 17 '22 13:09

Marcus