1

I am trying to replace the existing ps1 script that creates self signed certificate with C# code.

There are quite a lot of references like this that describes bulk of creating self-signed certificate using C# with .NET.

However there are couple of options that seem to be missing, and if I could get SO input, that would be amazing.

The options I am looking in C# / X509Certificate2 that are available in ps1 New-SelfSignedCertificate are followings :

-KeyUsageProperty All `
-CertStoreLocation $certStoreLocation `
-KeyExportPolicy Exportable `
-KeyProtection None `
-Type Custom

What are the equivalent class / properties available in C#?

Shintaro Takechi
  • 1,215
  • 1
  • 17
  • 39

1 Answers1

3

It's hard to answer accurately given that you haven't shared code. Extra harder because you don't seem to be describing problems (so your code might have all of these effects already)

-KeyUsageProperty All

This option changes the permissions on the persisted private key (e.g. if it's set to sign only then it'll fail if used for decryption)

The default for key creation is All, so you don't need to do anything there. If you have opinions about it, then you need to correctly configure the CngKey value backing an RSACng/ECDsaCng as part of key creation.

CngKeyCreationParameters.KeyUsage

The "-KeyUsageProperty" property/parameter seems to be different from the "-KeyUsage" property, which controls the KeyUsageExtension, though it might be used for generating some defaults. Since the snippet you linked to already builds the KeyUsageExtension this paragraph doesn't matter.

-CertStoreLocation $certStoreLocation

The powershell cmdlet creates the cert and saves it to an X509Store. The CertificateRequest API does not.

If you want to save the cert to a persisted store, you'll have to open the X509Store instance yourself and call Add. (Be sure to have a persisted private key, or export the created cert as a PFX, and import it back with X509KeyStorageFlags.PersistKeySet set.)

-KeyExportPolicy Exportable

If you're creating ephemeral keys (e.g. RSA.Create()), they're exportable. If you're creating persisted keys then it's part of your key creation.

CngKeyCreationParameters.ExportPolicy

-KeyProtection None

Another key creation option. The default is None. If you want something else, see CngKeyCreationParameters.UIPolicy

-Type Custom

The "-Type" parameter makes for some pre-populated values in the EKU extension. Since you're using Custom that means "don't pre-populate anything"... so... done!

bartonjs
  • 30,352
  • 2
  • 71
  • 111