I google it from web, find many examples to generate a new x509Certificate2
from a file in .Net, but there is no example to show how to generate a completely new x509Certificate2
from the beginning in .net.
Is there any one that can tell me how to do it in .net?
Checkout CertificateRequest (Name Space: System.Security.Cryptography.X509Certificates)...
public static X509Certificate2 GenerateSelfSignedCertificate()
{
string secp256r1Oid = "1.2.840.10045.3.1.7"; //oid for prime256v1(7) other identifier: secp256r1
string subjectName = "Self-Signed-Cert-Example";
var ecdsa = ECDsa.Create(ECCurve.CreateFromValue(secp256r1Oid));
var certRequest = new CertificateRequest($"CN={subjectName}", ecdsa, HashAlgorithmName.SHA256);
//add extensions to the request (just as an example)
//add keyUsage
certRequest.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, true));
X509Certificate2 generatedCert = certRequest.CreateSelfSigned(DateTimeOffset.Now.AddDays(-1), DateTimeOffset.Now.AddYears(10)); // generate the cert and sign!
X509Certificate2 pfxGeneratedCert = new X509Certificate2(generatedCert.Export(X509ContentType.Pfx)); //has to be turned into pfx or Windows at least throws a security credentials not found during sslStream.connectAsClient or HttpClient request...
return pfxGeneratedCert;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With