Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a completely new x509Certificate2 in .Net?

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?

like image 630
travellover Avatar asked Sep 01 '25 03:09

travellover


1 Answers

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;
}
like image 118
TwoFingerRightClick Avatar answered Sep 02 '25 19:09

TwoFingerRightClick