Search code examples
c#httpshttpclientx509certificate

c# https call with crt and key file with passphrase


I have a crt and key file along with a passphrase.

I am using these successfully via Postman to call an external API. How do I do this in c#?

I see examples of using X509Certificate with httpclient but Idont see any options for a constructor whereI can use with 2 files and set the passphrase


Solution

  • .NET won't do this for you easily.

    Your best bet, honestly, is to use something like OpenSSL to glue the cert and key together into a PFX.

    The answer shall now continue assuming you decided not to do that.

    There's no dearth of questions asking how to load a key without the certificate, e.g.:

    Once you've figured out how to load the key you have a key and a certificate, and they don't understand each other. There are solutions.

    The safest and easiest next step:

    If you are on .NET Core, or are using .NET Framework 4.7.2, you can use

    X509Certificate2 certWithKey = cert.CopyWithPrivateKey(privateKey);
    

    If you're adding certWithKey to an X509Store you either need to have used a persisted key, or export to PFX and import it back with X509KeyStorageFlags.PersistKeySet

    In distant second:

    If (all of):

    • You're on .NET Framework (not .NET Core)
    • Your key is an RSACryptoServiceProvider or a DSACryptoServiceProvider
    • Your key was loaded into a key container (!string.IsNullOrEmpty(key.CspKeyContainerInfo.KeyContainerName))
    • You either haven't gotten this certificate from an X509Store, or you aren't afraid of potentially unexpected side effects

    then you could use the setter of X509Certificate2.PrivateKey.

    Final thoughts

    There are some P/Invoke recommendations in the bottom of my answer to .NET Standard - Merge a certificate and a private key into a .pfx file programmatically for making a PFX. Once you've made a PFX you are back in "simple" territory.