0

I am using code found in How to create a self-signed certificate using C#? to generate self signed certificate in C#. Below is the code. Using this I am able to generate and add the certificate to My and Root store, however the certificate status says "The certificate has expired or is not yet valid", how to resolve this?

public X509Certificate2 CreateSelfSignedCertificate(string subjectName)
    {
        var dn = new CX500DistinguishedName();
        dn.Encode("CN=" + subjectName, X500NameFlags.XCN_CERT_NAME_STR_NONE);

        // create a new private key for the certificate
        CX509PrivateKey privateKey = new CX509PrivateKey();
        privateKey.ProviderName = "Microsoft Strong Cryptographic Provider";
        privateKey.Length = 1024;
        privateKey.KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE;
        privateKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_DECRYPT_FLAG | X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_KEY_AGREEMENT_FLAG;
        privateKey.MachineContext = true;
        privateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG;
        privateKey.Create();

        // Use the stronger SHA512 hashing algorithm
        var hashobj = new CObjectId();
        hashobj.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID,
            ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY,
            AlgorithmFlags.AlgorithmFlagsNone, "SHA1");

        // add extended key usage if you want - look at MSDN for a list of possible OIDs
        var oid = new CObjectId();
        oid.InitializeFromValue("1.3.6.1.5.5.7.3.1"); // SSL server
        var oidlist = new CObjectIds();
        oidlist.Add(oid);
        var eku = new CX509ExtensionEnhancedKeyUsage();
        eku.InitializeEncode(oidlist);

        CObjectId objOID = new CObjectId();
        CAlternativeName objAlternativeName1 = new CAlternativeName();

        CAlternativeNames objAlternativeNames = new CAlternativeNames();
        CX509ExtensionAlternativeNames objExtensionAlternativeNames = new CX509ExtensionAlternativeNames();

        string fqdn = GetFQDN();

        // Create the Issuer Alternative Name as if it were a Subject Alternative Name 
        objAlternativeName1.InitializeFromString(AlternativeNameType.XCN_CERT_ALT_NAME_DNS_NAME, fqdn);
        objAlternativeNames.Add(objAlternativeName1);


        objExtensionAlternativeNames.InitializeEncode(objAlternativeNames);

        // Create the self signing request
        var cert = new CX509CertificateRequestCertificate();
        cert.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, privateKey, "");
        cert.Subject = dn;
        cert.Issuer = dn; // the issuer and the subject are the same
        cert.NotBefore = DateTime.Now;
        // this cert expires immediately. Change to whatever makes sense for you
        //DateTime endtime = new DateTime(DateTime.Now.Year + 20, DateTime.Now.Month, DateTime.Now.Day);
        cert.NotAfter = cert.NotBefore.AddYears(20);
        cert.X509Extensions.Add((CX509Extension)objExtensionAlternativeNames);
        cert.X509Extensions.Add((CX509Extension)eku); // add the EKU
        cert.HashAlgorithm = hashobj; // Specify the hashing algorithm
        cert.Encode(); // encode the certificate

        // Do the final enrollment process
        var enroll = new CX509Enrollment();
        enroll.InitializeFromRequest(cert); // load the certificate
        enroll.CertificateFriendlyName = subjectName; // Optional: add a friendly name
        string csr = enroll.CreateRequest(); // Output the request in base64
                                             // and install it back as the response
        enroll.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedCertificate,
            csr, EncodingType.XCN_CRYPT_STRING_BASE64, ""); // no password
                                                            // output a base64 encoded PKCS#12 so we can import it back to the .Net security classes
        var base64encoded = enroll.CreatePFX("", // no password, this is for internal consumption
            PFXExportOptions.PFXExportChainWithRoot);

        X509Certificate2 certificate = new X509Certificate2(System.Convert.FromBase64String(base64encoded), "", X509KeyStorageFlags.Exportable);

        X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
        store.Open(OpenFlags.ReadWrite);
        store.Add(certificate);
        store.Close();

        // instantiate the target class with the PKCS#12 data (and the empty password)
        return certificate;
    }
Rem San
  • 367
  • 1
  • 5
  • 20

1 Answers1

0

You must provide UTC date time values:

   cert.NotBefore = DateTime.UtcNow;
Daniel Fisher lennybacon
  • 3,865
  • 1
  • 30
  • 38