5

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

Noel
  • 5,037
  • 9
  • 46
  • 69

1 Answers1

4

.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.

bartonjs
  • 30,352
  • 2
  • 71
  • 111
  • 1
    thanks @bartonjs for reply. So if I change to pfx(to make life easier) can I use X509Certificate( string fileName, SecureString password) ctr – Noel Mar 04 '18 at 17:21
  • 1
    @Noel yep. Though you should only bother with SecureString if you are prompting a user via `Console.ReadKey()`, the string overloads are better for most people’s needs – bartonjs Mar 04 '18 at 20:42