Sourav Parida
Sourav Parida

Reputation: 11

I want to create a p12 file based on a cert file and a key file

Both the cert and the key file are of type string. I tried using this:

 RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider();
rsaKey.ImportParameters(keyfile);
X509Certificate2 cert = new X509Certificate2(certfile);
cert.PrivateKey = rsaKey;
cert.Export(X509ContentType.Pkcs12, "xyz");
RestAsynchronicClient client = new RestAsynchronicClient(url, RestDataStandard.JSON, null, cert, logger);

Here I am getting conversion error in the second line. Conversion error from string to RSAParameter.

Upvotes: 1

Views: 1611

Answers (1)

bartonjs
bartonjs

Reputation: 33218

There's no automatic conversion from a file path, or file contents, to an RSAParameters; the RSACryptoServiceProvider is out of date and not recommended for new code, and the PrivateKey property on certificates is fully [Obsolete] in new versions of .NET.

With .NET 5+, this is easy:

byte[] pfxBytes;

using (X509Certificate2 cert = X509Certificate2.CreateFromPemFile(certFile, keyFile))
{
    pfxBytes = cert.Export(X509ContentType.Pkcs12, pfxPwd);
}

Or, in the style closer to the code you've written:

byte[] pfxBytes;

using (X509Certificate2 cert = new X509Certificate2(certFile))
using (RSA key = RSA.Create())
{
    key.ImportFromPem(File.ReadAllText(keyFile));

    using (X509Certificate2 certWithKey = cert.CopyWithPrivateKey(key))
    {
        pfxBytes = certWithKey.Export(X509ContentType.Pkcs12, pfxPwd);
    }
}

Your reference snippet then goes on to ignore the PFX/PKCS12 output and pass the cert to RestAsynchronicClient. Because of some idiosyncrasies on Windows, that generally won't work if you load the cert from this style. But, if you load the PFX into a new X509Certificate2 object, that'll be in a slightly different state and everything'll be happy.

RestAsynchronicClient client = new RestAsynchronicClient(
    url,
    RestDataStandard.JSON,
    null,
    new X509Certificate2(pfxBytes, pfxPwd),
    logger);

Upvotes: 1

Related Questions