I need to create a self-signed certificate (for local encryption – it’s not used to secure communications), using C#.
I’ve seen some implementations that use P/Invoke with Crypt32.dll, but they are complicated and it’s hard to update the parameters – and I would also like to avoid P/Invoke if at all possible.
I don’t need something that is cross platform – running only on Windows is good enough for me.
Ideally, the result would be an X509Certificate2 object that I can use to insert into the Windows certificate store or export to a PFX file.
This implementation uses the
CX509CertificateRequestCertificateCOM object (and friends – MSDN doc) fromcertenroll.dllto create a self signed certificate request and sign it.The example below is pretty straight forward (if you ignore the bits of COM stuff that goes on here) and there are a few parts of the code that are really optional (such as EKU) which are none-the-less useful and easy to adapt to your use.
The result can be added to a certificate store using
X509Storeor exported using theX509Certificate2methods.For a fully managed and not tied to Microsoft’s platform, and if you’re OK with Mono’s licensing, then you can look at X509CertificateBuilder from Mono.Security. Mono.Security is standalone from Mono, in that it doesn’t need the rest of Mono to run and can be used in any compliant .Net environment (e.g. Microsoft’s implementation).