Skip to content

Instantly share code, notes, and snippets.

@Unknown6656
Created November 10, 2022 14:25
Show Gist options
  • Save Unknown6656/ba1bc4ea9909880f57c3a23684f9c6b1 to your computer and use it in GitHub Desktop.
Save Unknown6656/ba1bc4ea9909880f57c3a23684f9c6b1 to your computer and use it in GitHub Desktop.
private static X509Certificate2 CreateSelfSignedCertificate(Guid? guid, bool is_server, (IEnumerable<string> Hosts, IEnumerable<IPAddress> Addresses)? alts)
{
string subject = guid?.ToString()?.Replace('-', '_') ?? ALT_DOMAIN;
if (is_server)
subject = $"<server {ALT_DOMAIN}>";
$"Generating X509 encryption certificates for \"{subject}\"...".LOG();
DateTime utc_now = DateTime.UtcNow.AddDays(-1);
DateTime utc_exp = utc_now.AddYears(10);
using RSA rsa = new RSACryptoServiceProvider(4096, new CspParameters(/*1, ROOT_AUTH, Guid.NewGuid().ToString()*/))
{
PersistKeyInCsp = false
};
CertificateRequest req = new CertificateRequest("CN=" + subject, rsa, HashAlgorithmName.SHA512, RSASignaturePadding.Pkcs1);
SubjectAlternativeNameBuilder alt = new SubjectAlternativeNameBuilder();
if (alts is null)
{
IPHostEntry entry = Dns.GetHostEntry(Dns.GetHostName());
alts = (entry.Aliases.Append(entry.HostName), entry.AddressList);
}
(IEnumerable<string> hosts, IEnumerable<IPAddress> addresses) = alts.Value;
foreach (string h in hosts.Append(ALT_DOMAIN))
alt.AddDnsName(h);
foreach (IPAddress ip in addresses)
alt.AddIpAddress(ip);
req.CertificateExtensions.Add(alt.Build());
req.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true));
req.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(req.PublicKey, false));
req.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature
| X509KeyUsageFlags.KeyAgreement
| X509KeyUsageFlags.NonRepudiation
| X509KeyUsageFlags.DataEncipherment
| X509KeyUsageFlags.KeyCertSign
| X509KeyUsageFlags.CrlSign, false));
req.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection
{
new Oid("2.5.29.37.0"),
new Oid("1.3.6.1.5.5.7.3.8"),
new Oid("1.3.6.1.5.5.7.3.1"),
new Oid("1.3.6.1.5.5.7.3.3"),
}, true));
X509Certificate2 pfx = req.CreateSelfSigned(utc_now, utc_exp);
return new X509Certificate2(pfx.Export(X509ContentType.Pfx));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment