I'm curious to know if there's a simplish way to create a self-signed certificate comparable to the below New-SelfSignedCertificate
command (other providers are OK too, for instance). I want to use only the .NET libraries without P/Invoke or external libraries such as Bouncy Castle or without calling PowerShell from the application.
New-SelfSignedCertificate -DnsName $certificateName -CertStoreLocation $certificateStore -KeyExportPolicy Exportable -Provider "Microsoft Enhanced RSA and AES Cryptographic Provider" -NotAfter $certificateNotAfter
I suppose the simplest alternative would be to call PowerShell or use a Nuget library such as Bouncy Castle, if this isn't doable without external facilities? Though it feels like that if I knew enough how to construct certificates, it'd be possible to create a byte array template or such and use that in the X509Certificate2
constructor.
It appears one would need to
public X509Certificate2 GenerateCertificate(string fileName, string password, string subjectName, StoreName storeName, DateTime endDate, DateTime notAfter, string provider = "Microsoft Enhanced RSA and AES Cryptographic Provider")
{
//Could provider be taken from https://stackoverflow.com/questions/43474902/generate-self-signed-rsa-2048-sha-256-certificate-pfx-file-using-openssl?
var newCertificate = new X509Certificate2(fileName, password, X509KeyStorageFlags.Exportable);
/*
# The following creates a self-signed certificate with one year of running time.
$currentDate = Get-Date
$certificateEndDate = $currentDate.AddYears(1)
$certificateNotAfter = $certificateEndDate.AddYears(1)
$certificateName = "https://www.test.com/test"
$certificateStore = "Cert:LocalMachineMy"
New-SelfSignedCertificate -DnsName $certificateName -CertStoreLocation $certificateStore -KeyExportPolicy Exportable -Provider "Microsoft Enhanced RSA and AES Cryptographic Provider" -NotAfter $certificateNotAfter
*/
}
<edit: It quickly became apparent there isn't a good way to do this with plain .NET.
A few more options I found:
A blog post Creating Authority-Signed and Self-Signed Certificates in .NET by Steve Syfuhs and another SO post using Mono extensions, Mono.Security won't set multiple KeyUsages. Apart from the choices already discussed, it's "something like this".
See Question&Answers more detail:os