private void SetBasicConstraints() { var bc = new CX509ExtensionBasicConstraints(); bc.InitializeEncode(false, -1); bc.Critical = true; ExtensionsToAdd.Add((CX509Extension)bc); }
private void AddBasicConstraints(CX509CertificateRequestCertificate cert) { // Add basic constraints var bc = new CX509ExtensionBasicConstraints(); bc.InitializeEncode(false, 0); bc.Critical = true; cert.X509Extensions.Add((CX509Extension)bc); }
public static X509Certificate2 CreateCertificate(Certificate crt) { bool isCA = !crt.SignByCertificateAuthority; // create DN for subject and issuer var dn = new CX500DistinguishedName(); dn.Encode(GetEncodedDistinguishedName(crt), X500NameFlags.XCN_CERT_NAME_STR_NONE); // create a new private key for the certificate CX509PrivateKey privateKey = new CX509PrivateKey { ProviderName = "Microsoft Base Cryptographic Provider v1.0", MachineContext = crt.MachineContext, Length = crt.KeyLength, KeySpec = X509KeySpec.XCN_AT_SIGNATURE, // use is not limited ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG }; privateKey.Create(); var hashobj = new CObjectId(); hashobj.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID, ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY, AlgorithmFlags.AlgorithmFlagsNone, crt.DigestAlgorithm); CERTENROLLLib.X509KeyUsageFlags x509KeyUsageFlags; CX509ExtensionBasicConstraints bc = new CX509ExtensionBasicConstraints(); if (isCA) { x509KeyUsageFlags = CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_DIGITAL_SIGNATURE_KEY_USAGE | CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_KEY_CERT_SIGN_KEY_USAGE | CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_CRL_SIGN_KEY_USAGE | CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_OFFLINE_CRL_SIGN_KEY_USAGE; bc.InitializeEncode(true, -1); bc.Critical = true; } else { x509KeyUsageFlags = CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_KEY_ENCIPHERMENT_KEY_USAGE | CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_DIGITAL_SIGNATURE_KEY_USAGE; if (crt.CertificateType == CertificateType.ClientCertificate) { x509KeyUsageFlags |= CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_NON_REPUDIATION_KEY_USAGE; } if (crt.CertificateType == CertificateType.ServerCertificate) { x509KeyUsageFlags |= CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_NON_REPUDIATION_KEY_USAGE; } bc.InitializeEncode(false, -1); bc.Critical = false; } CX509ExtensionKeyUsage keyUsage = new CX509ExtensionKeyUsage(); keyUsage.InitializeEncode(x509KeyUsageFlags); keyUsage.Critical = false; // SAN var canList = new List <CAlternativeName>(); foreach (var sanItem in crt.SANList) { if (!string.IsNullOrWhiteSpace(sanItem.Value)) { var can = new CAlternativeName(); switch (sanItem.Type) { case Certificate.SANType.DNS: can.InitializeFromString(AlternativeNameType.XCN_CERT_ALT_NAME_DNS_NAME, sanItem.Value); break; case Certificate.SANType.IP: can.InitializeFromRawData(AlternativeNameType.XCN_CERT_ALT_NAME_IP_ADDRESS, EncodingType.XCN_CRYPT_STRING_BASE64, Convert.ToBase64String(IPAddress.Parse(sanItem.Value).GetAddressBytes())); break; case Certificate.SANType.URI: can.InitializeFromString(AlternativeNameType.XCN_CERT_ALT_NAME_URL, sanItem.Value); break; case Certificate.SANType.email: can.InitializeFromString(AlternativeNameType.XCN_CERT_ALT_NAME_RFC822_NAME, sanItem.Value); break; } canList.Add(can); } } CX509ExtensionAlternativeNames san = null; if (canList.Any()) { san = new CX509ExtensionAlternativeNames(); var cans = new CAlternativeNames(); foreach (var item in canList) { cans.Add(item); } san.InitializeEncode(cans); } CX509ExtensionEnhancedKeyUsage eku = null; if (crt.CertificateType != CertificateType.None) { const string XCN_OID_PKIX_KP_SERVER_AUTH = "1.3.6.1.5.5.7.3.1"; const string XCN_OID_PKIX_KP_CLIENT_AUTH = "1.3.6.1.5.5.7.3.2"; var oid = new CObjectId(); if (crt.CertificateType == CertificateType.ServerCertificate) { oid.InitializeFromValue(XCN_OID_PKIX_KP_SERVER_AUTH); } if (crt.CertificateType == CertificateType.ClientCertificate) { oid.InitializeFromValue(XCN_OID_PKIX_KP_CLIENT_AUTH); } var oidlist = new CObjectIds(); oidlist.Add(oid); eku = new CX509ExtensionEnhancedKeyUsage(); eku.InitializeEncode(oidlist); } // Create the self signing request var cereq = new CX509CertificateRequestCertificate(); cereq.InitializeFromPrivateKey(crt.MachineContext ? X509CertificateEnrollmentContext.ContextMachine : X509CertificateEnrollmentContext.ContextUser, privateKey, ""); cereq.Subject = dn; cereq.Issuer = dn; cereq.NotBefore = DateTime.UtcNow.AddDays(-1); cereq.NotAfter = DateTime.UtcNow.AddDays(crt.Lifetime.Value); if (crt.SignByCertificateAuthority) { var issuer = MyCurrentUserX509Store.Certificates .Find(X509FindType.FindByThumbprint, crt.CertificateAuthority, false) .OfType <X509Certificate2>() .Where(c => c.HasPrivateKey).FirstOrDefault() ?? throw new Exception("Issuer not found: " + crt.CertificateAuthority); cereq.SignerCertificate = new CSignerCertificate(); cereq.SignerCertificate.Initialize(false, X509PrivateKeyVerify.VerifyNone, EncodingType.XCN_CRYPT_STRING_HEX, issuer.GetRawCertDataString()); cereq.Issuer = new CX500DistinguishedName(); cereq.Issuer.Encode(issuer.Subject, X500NameFlags.XCN_CERT_NAME_STR_NONE); } cereq.X509Extensions.Add((CX509Extension)keyUsage); if (eku != null) { cereq.X509Extensions.Add((CX509Extension)eku); // EnhancedKeyUsage } if (bc != null) { cereq.X509Extensions.Add((CX509Extension)bc); // ExtensionBasicConstraints } if (san != null) { cereq.X509Extensions.Add((CX509Extension)san); // SAN } cereq.HashAlgorithm = hashobj; // Specify the hashing algorithm cereq.Encode(); // encode the certificate // Do the final enrollment process var enroll = new CX509Enrollment(); enroll.InitializeFromRequest(cereq); // 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); // instantiate the target class with the PKCS#12 data (and the empty password) var x509Certificate2 = new X509Certificate2( Convert.FromBase64String(base64encoded), "", X509KeyStorageFlags.Exportable); // mark the private key as exportable (this is usually what you want to do) if (isCA) { X509Store rootStore = null; try { rootStore = new X509Store(StoreName.Root, crt.MachineContext ? StoreLocation.LocalMachine : StoreLocation.CurrentUser); rootStore.Open(OpenFlags.ReadWrite); // install to CA store var crtPub = new X509Certificate2(x509Certificate2) { PrivateKey = null }; rootStore.Add(crtPub); crtPub.Reset(); } catch { // ignore when adding to trust root failed } finally { rootStore?.Close(); } } crt.Value = x509Certificate2; return(x509Certificate2); }
// https://github.com/asafga-gsr-it/CertIntegration/blob/master/CertificateAdmin/CertificateAdmin/obj/Release/Package/PackageTmp/Certificate.cs // https://www.sysadmins.lv/blog-en/introducing-to-certificate-enrollment-apis-part-2-creating-offline-requests.aspx /* * public static X509Certificate2 CreateSelfSignedCA(string subjectName, DateTime notAfterUtc, bool machineContext) * { * // create DN for subject and issuer * var dn = new CX500DistinguishedName(); * dn.Encode("CN=" + EscapeDNComponent(subjectName), X500NameFlags.XCN_CERT_NAME_STR_NONE); * * // create a new private key for the certificate * CX509PrivateKey privateKey = new CX509PrivateKey(); * privateKey.ProviderName = "Microsoft Base Cryptographic Provider v1.0"; * privateKey.MachineContext = machineContext; * privateKey.Length = 2048; * privateKey.KeySpec = X509KeySpec.XCN_AT_SIGNATURE; // use is not limited * privateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG; * privateKey.Create(); * * var hashobj = new CObjectId(); * hashobj.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID, * ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY, * AlgorithmFlags.AlgorithmFlagsNone, "SHA256"); // https://docs.microsoft.com/en-us/windows/win32/seccng/cng-algorithm-identifiers * * CX509ExtensionKeyUsage keyUsage = new CX509ExtensionKeyUsage(); * keyUsage.InitializeEncode( * CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_DIGITAL_SIGNATURE_KEY_USAGE | * CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_KEY_CERT_SIGN_KEY_USAGE | * CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_CRL_SIGN_KEY_USAGE | * CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_OFFLINE_CRL_SIGN_KEY_USAGE); * * CX509ExtensionBasicConstraints bc = new CX509ExtensionBasicConstraints(); * bc.InitializeEncode(true, -1); // None * bc.Critical = true; * * // 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"); // Server Authentication * var oidlist = new CObjectIds(); * oidlist.Add(oid); * var eku = new CX509ExtensionEnhancedKeyUsage(); * eku.InitializeEncode(oidlist); * * // Create the self signing request * var cert = new CX509CertificateRequestCertificate(); * * cert.InitializeFromPrivateKey(machineContext ? X509CertificateEnrollmentContext.ContextMachine: X509CertificateEnrollmentContext.ContextUser, privateKey, ""); * cert.Subject = cert.Issuer = dn; // the issuer and the subject are the same * cert.NotBefore = DateTime.UtcNow.AddDays(-1); * cert.NotAfter = notAfterUtc; * cert.X509Extensions.Add((CX509Extension)keyUsage); * cert.X509Extensions.Add((CX509Extension)eku); // add the EKU * cert.X509Extensions.Add((CX509Extension)bc); * 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 * * // install to MY store * 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); * * // instantiate the target class with the PKCS#12 data (and the empty password) * var x509Certificate2 = new X509Certificate2( * System.Convert.FromBase64String(base64encoded), "", * // mark the private key as exportable (this is usually what you want to do) * X509KeyStorageFlags.Exportable * ); * * X509Store rootStore = null; * try * { * rootStore = new X509Store(StoreName.Root, machineContext ? StoreLocation.LocalMachine : StoreLocation.CurrentUser); * rootStore.Open(OpenFlags.ReadWrite); * // install to CA store * var crtPub = new X509Certificate2(x509Certificate2) { PrivateKey = null }; * rootStore.Add(crtPub); * crtPub.Reset(); * } * catch * { * // ignore when adding to trust root failed * } * finally * { * rootStore?.Close(); * } * * return x509Certificate2; * } */ public static X509Certificate2 CreateCertificate(string subjectName, string hostname, DateTime notAfterUtc, X509Certificate issuer, bool machineContext) { CSignerCertificate signerCertificate = new CSignerCertificate(); signerCertificate.Initialize(false, X509PrivateKeyVerify.VerifyNone, EncodingType.XCN_CRYPT_STRING_HEX, issuer.GetRawCertDataString()); // create DN for subject and issuer var dn = new CX500DistinguishedName(); dn.Encode("CN=" + EscapeDNComponent(subjectName), X500NameFlags.XCN_CERT_NAME_STR_NONE); // create a new private key for the certificate CX509PrivateKey privateKey = new CX509PrivateKey(); privateKey.ProviderName = "Microsoft Base Cryptographic Provider v1.0"; privateKey.MachineContext = machineContext; privateKey.Length = 2048; privateKey.KeySpec = X509KeySpec.XCN_AT_SIGNATURE; // use is not limited privateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG; privateKey.Create(); var hashobj = new CObjectId(); hashobj.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID, ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY, AlgorithmFlags.AlgorithmFlagsNone, "SHA256"); CX509ExtensionKeyUsage keyUsage = new CX509ExtensionKeyUsage(); keyUsage.InitializeEncode( CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_DATA_ENCIPHERMENT_KEY_USAGE | CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_KEY_ENCIPHERMENT_KEY_USAGE | CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_DIGITAL_SIGNATURE_KEY_USAGE); CX509ExtensionBasicConstraints bc = new CX509ExtensionBasicConstraints(); bc.InitializeEncode(false, 0); bc.Critical = false; // SAN CX509ExtensionAlternativeNames san = null; if (!string.IsNullOrEmpty(hostname)) { CAlternativeNames ians; if (IPAddress.TryParse(hostname, out var ip)) { var ian = new CAlternativeName(); ian.InitializeFromRawData(AlternativeNameType.XCN_CERT_ALT_NAME_IP_ADDRESS, EncodingType.XCN_CRYPT_STRING_BASE64, Convert.ToBase64String(ip.GetAddressBytes())); ians = new CAlternativeNames { ian }; } else { var ian = new CAlternativeName(); ian.InitializeFromString(AlternativeNameType.XCN_CERT_ALT_NAME_DNS_NAME, hostname); var ianStar = new CAlternativeName(); ianStar.InitializeFromString(AlternativeNameType.XCN_CERT_ALT_NAME_DNS_NAME, "*." + hostname); // wildcard ians = new CAlternativeNames { ian, ianStar }; } san = new CX509ExtensionAlternativeNames(); san.InitializeEncode(ians); } // 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); var dnIssuer = new CX500DistinguishedName(); dnIssuer.Encode(issuer.Subject, X500NameFlags.XCN_CERT_NAME_STR_NONE); // Create the self signing request var cert = new CX509CertificateRequestCertificate(); cert.InitializeFromPrivateKey(machineContext ? X509CertificateEnrollmentContext.ContextMachine : X509CertificateEnrollmentContext.ContextUser, privateKey, ""); cert.Subject = dn; cert.Issuer = dnIssuer; cert.SignerCertificate = signerCertificate; cert.NotBefore = DateTime.UtcNow.AddDays(-1); cert.NotAfter = notAfterUtc; cert.X509Extensions.Add((CX509Extension)keyUsage); cert.X509Extensions.Add((CX509Extension)eku); // EnhancedKeyUsage cert.X509Extensions.Add((CX509Extension)bc); // ExtensionBasicConstraints if (san != null) { cert.X509Extensions.Add((CX509Extension)san); // SAN } 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); // instantiate the target class with the PKCS#12 data (and the empty password) var x509Certificate2 = new X509Certificate2( Convert.FromBase64String(base64encoded), "", X509KeyStorageFlags.Exportable); // mark the private key as exportable (this is usually what you want to do) return(x509Certificate2); }
public static X509Certificate2 CreateCertificate(string certSubject, bool isCA) { string CAsubject = certSubject; CX500DistinguishedName dn = new CX500DistinguishedName(); dn.Encode("CN=" + CAsubject, X500NameFlags.XCN_CERT_NAME_STR_NONE); string strRfc822Name = certSubject; CAlternativeName objRfc822Name = new CAlternativeName(); CAlternativeNames objAlternativeNames = new CAlternativeNames(); CX509ExtensionAlternativeNames objExtensionAlternativeNames = new CX509ExtensionAlternativeNames(); // Set Alternative RFC822 Name objRfc822Name.InitializeFromString(AlternativeNameType.XCN_CERT_ALT_NAME_DNS_NAME, strRfc822Name); // Set Alternative Names objAlternativeNames.Add(objRfc822Name); objExtensionAlternativeNames.InitializeEncode(objAlternativeNames); //objPkcs10.X509Extensions.Add((CX509Extension)objExtensionAlternativeNames); //Issuer Property for cleanup string issuer = "__Interceptor_Trusted_Root"; CX500DistinguishedName issuerdn = new CX500DistinguishedName(); issuerdn.Encode("CN=" + issuer, X500NameFlags.XCN_CERT_NAME_STR_NONE); // Create a new Private Key CX509PrivateKey key = new CX509PrivateKey(); key.ProviderName = "Microsoft Enhanced RSA and AES Cryptographic Provider"; //"Microsoft Enhanced Cryptographic Provider v1.0" // Set CAcert to 1 to be used for Signature if (isCA) { key.KeySpec = X509KeySpec.XCN_AT_SIGNATURE; } else { key.KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE; } key.Length = 2048; key.MachineContext = true; key.Create(); // Create Attributes //var serverauthoid = new X509Enrollment.CObjectId(); CObjectId serverauthoid = new CObjectId(); serverauthoid.InitializeFromValue("1.3.6.1.5.5.7.3.1"); CObjectIds ekuoids = new CObjectIds(); ekuoids.Add(serverauthoid); CX509ExtensionEnhancedKeyUsage ekuext = new CX509ExtensionEnhancedKeyUsage(); ekuext.InitializeEncode(ekuoids); CX509CertificateRequestCertificate cert = new CX509CertificateRequestCertificate(); cert.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, key, ""); cert.Subject = dn; cert.Issuer = issuerdn; cert.NotBefore = (DateTime.Now).AddDays(-1); //Backup One day to Avoid Timing Issues cert.NotAfter = cert.NotBefore.AddDays(90); //Arbitrary... Change to persist longer... //Use Sha256 CObjectId hashAlgorithmObject = new CObjectId(); hashAlgorithmObject.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID, 0, 0, "SHA256"); cert.HashAlgorithm = hashAlgorithmObject; cert.X509Extensions.Add((CX509Extension)ekuext); cert.X509Extensions.Add((CX509Extension)objExtensionAlternativeNames); //https://blogs.msdn.microsoft.com/alejacma/2011/11/07/how-to-add-subject-alternative-name-to-your-certificate-requests-c/ if (isCA) { CX509ExtensionBasicConstraints basicConst = new CX509ExtensionBasicConstraints(); basicConst.InitializeEncode(true, 1); cert.X509Extensions.Add((CX509Extension)basicConst); } else { var store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); X509Certificate2Collection signer = store.Certificates.Find(X509FindType.FindBySubjectName, "__Interceptor_Trusted_Root", false); CSignerCertificate signerCertificate = new CSignerCertificate(); signerCertificate.Initialize(true, 0, EncodingType.XCN_CRYPT_STRING_HEX, signer[0].Thumbprint); cert.SignerCertificate = signerCertificate; } cert.Encode(); CX509Enrollment enrollment = new CX509Enrollment(); enrollment.InitializeFromRequest(cert); string certdata = enrollment.CreateRequest(0); enrollment.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedCertificate, certdata, 0, ""); if (isCA) { //Install CA Root Certificate X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); X509Certificate2Collection certList = store.Certificates.Find(X509FindType.FindBySubjectName, "__Interceptor_Trusted_Root", false); store.Close(); X509Store rootStore = new X509Store(StoreName.Root, StoreLocation.LocalMachine); rootStore.Open(OpenFlags.ReadWrite); X509Certificate2Collection rootcertList = rootStore.Certificates.Find(X509FindType.FindBySubjectName, "__Interceptor_Trusted_Root", false); rootStore.Add(certList[0]); rootStore.Close(); return(certList[0]); } else { //Return Per Domain Cert X509Store xstore = new X509Store(StoreName.My, StoreLocation.LocalMachine); xstore.Open(OpenFlags.ReadOnly); X509Certificate2Collection certList = xstore.Certificates.Find(X509FindType.FindBySubjectName, certSubject, false); xstore.Close(); return(certList[0]); } }
public X509Certificate2 CreateSelfSignedCertificate(string FriendlyName, string SubjectName) { try { // Create DN for Subject CX500DistinguishedName dnSubject = new CX500DistinguishedName(); dnSubject.Encode(String.Format(@"CN={0}", SubjectName), X500NameFlags.XCN_CERT_NAME_STR_NONE); // Create DN for Issuer CX500DistinguishedName dnIssuer = new CX500DistinguishedName(); dnIssuer.Encode(String.Format(@"CN={0}", IssuerName), X500NameFlags.XCN_CERT_NAME_STR_NONE); // Use the stronger SHA512 hashing algorithm CObjectId HashAlgorithm = new CObjectId(); HashAlgorithm.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID, ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY, AlgorithmFlags.AlgorithmFlagsNone, strAlgorithmName); // add extended key usage if you want - look at MSDN for a list of possible OIDs CObjectId oid1 = new CObjectId(); oid1.InitializeFromValue("1.3.6.1.5.5.7.3.1"); // SSL Server CObjectId oid2 = new CObjectId(); oid2.InitializeFromValue("1.3.6.1.5.5.7.3.2"); // SSL Client CObjectIds oidlist = new CObjectIds(); oidlist.Add(oid1); oidlist.Add(oid2); CX509ExtensionEnhancedKeyUsage eku = new CX509ExtensionEnhancedKeyUsage(); eku.InitializeEncode(oidlist); CX509ExtensionAlternativeNames objExtensionAlternativeNames = new CX509ExtensionAlternativeNames(); { CAlternativeNames altNames = new CAlternativeNames(); CAlternativeName dnsLocalHost = new CAlternativeName(); dnsLocalHost.InitializeFromString(AlternativeNameType.XCN_CERT_ALT_NAME_DNS_NAME, "LOCALHOST"); altNames.Add(dnsLocalHost); CAlternativeName dnsHostname = new CAlternativeName(); dnsHostname.InitializeFromString(AlternativeNameType.XCN_CERT_ALT_NAME_DNS_NAME, Environment.MachineName); altNames.Add(dnsHostname); foreach (var ipAddress in Dns.GetHostAddresses(Dns.GetHostName())) { if ((ipAddress.AddressFamily == AddressFamily.InterNetwork) && !IPAddress.IsLoopback(ipAddress)) { CAlternativeName dns = new CAlternativeName(); dns.InitializeFromString(AlternativeNameType.XCN_CERT_ALT_NAME_DNS_NAME, ipAddress.ToString()); altNames.Add(dns); } } objExtensionAlternativeNames.InitializeEncode(altNames); } //CX509ExtensionSmimeCapabilities smimeCapabilities = new CX509ExtensionSmimeCapabilities(); //smimeCapabilities.SmimeCapabilities.AddAvailableSmimeCapabilities(false); CX509ExtensionBasicConstraints basicConst = new CX509ExtensionBasicConstraints(); basicConst.InitializeEncode(dnSubject.Name == dnIssuer.Name ? true : false, 1); // Key Usage Extension CX509ExtensionKeyUsage objExtensionKeyUsage = new CX509ExtensionKeyUsage(); objExtensionKeyUsage.InitializeEncode( CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_DIGITAL_SIGNATURE_KEY_USAGE | CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_NON_REPUDIATION_KEY_USAGE | CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_KEY_ENCIPHERMENT_KEY_USAGE | CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_DATA_ENCIPHERMENT_KEY_USAGE | CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_KEY_CERT_SIGN_KEY_USAGE ); // Create the self signing request CX509CertificateRequestCertificate cert = new CX509CertificateRequestCertificate(); cert.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, PrivateKey, ""); cert.Subject = dnSubject; cert.Issuer = dnIssuer; cert.NotBefore = DateTime.Today.AddDays(-1); cert.NotAfter = DateTime.Today.AddYears(ExpirationLengthInYear); cert.X509Extensions.Add((CX509Extension)eku); // add the EKU cert.X509Extensions.Add((CX509Extension)objExtensionAlternativeNames); cert.X509Extensions.Add((CX509Extension)objExtensionKeyUsage); cert.X509Extensions.Add((CX509Extension)basicConst); //cert.X509Extensions.Add((CX509Extension)smimeCapabilities); cert.HashAlgorithm = HashAlgorithm; // Specify the hashing algorithm cert.Encode(); // encode the certificate // Do the final enrollment process CX509Enrollment enroll = new CX509Enrollment(); enroll.InitializeFromRequest(cert); // load the certificate enroll.CertificateFriendlyName = FriendlyName; // Optional: add a friendly name string csr = enroll.CreateRequest(); // Output the request in base64 and install it back as the response // no password output a base64 encoded PKCS#12 so we can import it back to the .Net security classes enroll.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedCertificate, csr, EncodingType.XCN_CRYPT_STRING_BASE64, ""); // no password, this is for internal consumption var base64encoded = enroll.CreatePFX("", PFXExportOptions.PFXExportChainWithRoot); // instantiate the target class with the PKCS#12 data (and the empty password) // mark the private key as exportable (this is usually what you want to do) return(new X509Certificate2(Convert.FromBase64String(base64encoded), "", X509KeyStorageFlags.Exportable)); } catch (Exception ex) { throw new Exception(ex.Message); } }
public static X509Certificate2 CreateCertificate(string subjectName, int days, X509Certificate2 issuer) { CSignerCertificate signerCertificate = new CSignerCertificate(); signerCertificate.Initialize(true, X509PrivateKeyVerify.VerifyNone, EncodingType.XCN_CRYPT_STRING_HEX, issuer.GetRawCertDataString()); // create DN for subject and issuer 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 Base Cryptographic Provider v1.0"; privateKey.MachineContext = true; privateKey.Length = 2048; privateKey.KeySpec = X509KeySpec.XCN_AT_SIGNATURE; // use is not limited privateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG; privateKey.Create(); var hashobj = new CObjectId(); hashobj.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID, ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY, AlgorithmFlags.AlgorithmFlagsNone, "SHA256"); CX509ExtensionKeyUsage keyUsage = new CX509ExtensionKeyUsage(); keyUsage.InitializeEncode(CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_DATA_ENCIPHERMENT_KEY_USAGE | CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_KEY_ENCIPHERMENT_KEY_USAGE | CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_DIGITAL_SIGNATURE_KEY_USAGE); CX509ExtensionBasicConstraints bc = new CX509ExtensionBasicConstraints(); bc.InitializeEncode(false, 0); bc.Critical = false; // 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); var dnIssuer = new CX500DistinguishedName(); dnIssuer.Encode(issuer.Subject, X500NameFlags.XCN_CERT_NAME_STR_NONE); // Create the self signing request var cert = new CX509CertificateRequestCertificate(); cert.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, privateKey, ""); cert.Subject = dn; cert.Issuer = dnIssuer; cert.SignerCertificate = signerCertificate; cert.NotBefore = DateTime.UtcNow.Date.AddDays(-1); cert.NotAfter = DateTime.UtcNow.Date.AddDays(days); cert.X509Extensions.Add((CX509Extension)keyUsage); cert.X509Extensions.Add((CX509Extension)eku); // add the EKU cert.X509Extensions.Add((CX509Extension)bc); /* * var ski = new CX509ExtensionAuthorityKeyIdentifier(); * ski.InitializeEncode(EncodingType.XCN_CRYPT_STRING_BINARY, cert.PublicKey.ComputeKeyIdentifier(KeyIdentifierHashAlgorithm.SKIHashSha1, EncodingType.XCN_CRYPT_STRING_BINARY)); * cert.X509Extensions.Add((CX509Extension)ski); */ 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); // instantiate the target class with the PKCS#12 data (and the empty password) var x509Certificate2 = new System.Security.Cryptography.X509Certificates.X509Certificate2( System.Convert.FromBase64String(base64encoded), "", // mark the private key as exportable (this is usually what you want to do) System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable); return(x509Certificate2); }
public static X509Certificate2 CreateCodeSigningCertificate(string subjectName, string oid, byte[] data) { var dn = new CX500DistinguishedName(); dn.Encode(subjectName, X500NameFlags.XCN_CERT_NAME_STR_NONE); // create a new private key for the certificate CX509PrivateKey privateKey = new CX509PrivateKey(); // http://blogs.technet.com/b/pki/archive/2009/08/05/how-to-create-a-web-server-ssl-certificate-manually.aspx privateKey.ProviderName = "Microsoft RSA SChannel Cryptographic Provider"; privateKey.Length = 2048; privateKey.KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE; privateKey.MachineContext = false; privateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_PLAINTEXT_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, "SHA512"); // add code signing EKUs var oidCodeSigning = new CObjectId(); oidCodeSigning.InitializeFromValue("1.3.6.1.5.5.7.3.3"); var oidLifetimeSigning = new CObjectId(); oidLifetimeSigning.InitializeFromValue("1.3.6.1.4.1.311.10.3.13"); var oidlist = new CObjectIds(); oidlist.Add(oidCodeSigning); oidlist.Add(oidLifetimeSigning); var eku = new CX509ExtensionEnhancedKeyUsage(); eku.InitializeEncode(oidlist); var keyUsage = new CX509ExtensionKeyUsage(); keyUsage.InitializeEncode( // Digital Signature, Key Encipherment (a0) X509KeyUsageFlags.XCN_CERT_DIGITAL_SIGNATURE_KEY_USAGE | X509KeyUsageFlags.XCN_CERT_KEY_ENCIPHERMENT_KEY_USAGE); // add CA Restriction (not a CA) var caRestriction = new CX509ExtensionBasicConstraints(); caRestriction.InitializeEncode(false, -1); // add the arbitrary data var ourExtensionOid = new CObjectId(); ourExtensionOid.InitializeFromValue(oid); var ourExtension = new CX509Extension(); ourExtension.Initialize(ourExtensionOid, EncodingType.XCN_CRYPT_STRING_BASE64, Convert.ToBase64String(data)); // Create the self signing request var cert = new CX509CertificateRequestCertificate(); cert.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextUser, privateKey, ""); cert.Subject = dn; cert.Issuer = dn; cert.NotBefore = DateTime.Now.AddDays(-1); cert.NotAfter = DateTime.Now.AddYears(30); cert.X509Extensions.Add((CX509Extension)eku); cert.X509Extensions.Add((CX509Extension)caRestriction); cert.X509Extensions.Add((CX509Extension)keyUsage); cert.X509Extensions.Add((CX509Extension)ourExtension); cert.HashAlgorithm = hashobj; cert.Encode(); var enroll = new CX509Enrollment(); enroll.InitializeFromRequest(cert); var csr = enroll.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64); enroll.InstallResponse( InstallResponseRestrictionFlags.AllowUntrustedCertificate, csr, EncodingType.XCN_CRYPT_STRING_BASE64, ""); return(new X509Certificate2(Convert.FromBase64String(enroll.Certificate[EncodingType.XCN_CRYPT_STRING_BASE64]))); }