Created
February 28, 2023 02:06
-
-
Save danzuep/681deb7b2b05ca8c84f5a7003b8b298a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SslCertificateHelper | |
{ | |
[SupportedOSPlatform("windows")] | |
public static X509Certificate2? GetX509Certificate2(string subject = "CN=localhost") | |
{ | |
X509Certificate2? certificate = null; | |
using var certStore = new X509Store(StoreName.My, StoreLocation.LocalMachine); | |
certStore.Open(OpenFlags.ReadWrite | OpenFlags.OpenExistingOnly); | |
var certs = certStore.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, subject, false); | |
if (certs.Count > 0) | |
{ | |
certificate = certs[0]; | |
} | |
else | |
{ | |
certificate = CreateSelfSignedCertificate(subject); | |
if (certificate != null) | |
certStore.Add(certificate); | |
} | |
return certificate; | |
} | |
[SupportedOSPlatform("windows")] | |
private static X509Certificate2? CreateSelfSignedCertificate(string subject = "CN=localhost") | |
{ | |
using var rsa = new RSACryptoServiceProvider(4096, new CspParameters(24, "Microsoft Enhanced RSA and AES Cryptographic Provider", Guid.NewGuid().ToString())); | |
var req = new CertificateRequest(subject, rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); | |
var cert = req.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddYears(1)); | |
var password = Guid.NewGuid().ToString(); | |
var rsaCert = new X509Certificate2(cert.Export(X509ContentType.Pfx, password), password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); | |
return rsaCert; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment