public string CreateRequest(string cn, string ou, string o, string l, string s, string c, string oid, int keylength) { var objCSPs = new CCspInformations(); objCSPs.AddAvailableCsps(); var objPrivateKey = new CX509PrivateKey(); objPrivateKey.Length = keylength; objPrivateKey.KeySpec = X509KeySpec.XCN_AT_SIGNATURE; //http://msdn.microsoft.com/en-us/library/windows/desktop/aa379409(v=vs.85).aspx objPrivateKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_ALL_USAGES; //http://msdn.microsoft.com/en-us/library/windows/desktop/aa379417(v=vs.85).aspx objPrivateKey.MachineContext = false; //http://msdn.microsoft.com/en-us/library/windows/desktop/aa379024(v=vs.85).aspx objPrivateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG; //http://msdn.microsoft.com/en-us/library/windows/desktop/aa379412(v=vs.85).aspx objPrivateKey.CspInformations = objCSPs; objPrivateKey.Create(); var objPkcs10 = new CX509CertificateRequestPkcs10(); objPkcs10.InitializeFromPrivateKey( X509CertificateEnrollmentContext.ContextUser, //http://msdn.microsoft.com/en-us/library/windows/desktop/aa379399(v=vs.85).aspx objPrivateKey, string.Empty); var objExtensionKeyUsage = new CX509ExtensionKeyUsage(); objExtensionKeyUsage.InitializeEncode( CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_DIGITAL_SIGNATURE_KEY_USAGE | // http://msdn.microsoft.com/en-us/library/windows/desktop/aa379410(v=vs.85).aspx CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_NON_REPUDIATION_KEY_USAGE | // http://msdn.microsoft.com/en-us/library/windows/desktop/aa379410(v=vs.85).aspx CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_KEY_ENCIPHERMENT_KEY_USAGE | // http://msdn.microsoft.com/en-us/library/windows/desktop/aa379410(v=vs.85).aspx CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_DATA_ENCIPHERMENT_KEY_USAGE); // http://msdn.microsoft.com/en-us/library/windows/desktop/aa379410(v=vs.85).aspx objPkcs10.X509Extensions.Add((CX509Extension)objExtensionKeyUsage); var objObjectId = new CObjectId(); var objObjectIds = new CObjectIds(); var objX509ExtensionEnhancedKeyUsage = new CX509ExtensionEnhancedKeyUsage(); //objObjectId.InitializeFromValue("1.3.6.1.5.5.7.3.1"); objObjectId.InitializeFromValue(oid); //Some info about OIDS: http://www.alvestrand.no/objectid/1.3.6.1.5.5.7.3.html objObjectIds.Add(objObjectId); objX509ExtensionEnhancedKeyUsage.InitializeEncode(objObjectIds); objPkcs10.X509Extensions.Add((CX509Extension)objX509ExtensionEnhancedKeyUsage); // TODO: Create CERTS with SAN: http://msdn.microsoft.com/en-us/library/windows/desktop/aa378081(v=vs.85).aspx /* var test3 = new CX509ExtensionAlternativeNames(); var test4 = new CAlternativeName(); var test2 = new CAlternativeNames(); test4.InitializeFromString(AlternativeNameType.XCN_CERT_ALT_NAME_DNS_NAME,"CRAP.no"); test2.Add(test4); test3.InitializeEncode(test2); */ //objPkcs10.X509Extensions.Add((CX509Extension)); var objDN = new CX500DistinguishedName(); var subjectName = "CN = " + cn + ",OU = " + ou + ",O = " + o + ",L = " + l + ",S = " + s + ",C = " + c; objDN.Encode(subjectName, X500NameFlags.XCN_CERT_NAME_STR_NONE); //http://msdn.microsoft.com/en-us/library/windows/desktop/aa379394(v=vs.85).aspx objPkcs10.Subject = objDN; var objEnroll = new CX509Enrollment(); objEnroll.InitializeFromRequest(objPkcs10); var strRequest = objEnroll.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64); //http://msdn.microsoft.com/en-us/library/windows/desktop/aa374936(v=vs.85).aspx return strRequest; }
// http://stackoverflow.com/questions/13806299/how-to-create-a-self-signed-certificate-using-c private static X509Certificate2 CreateSelfSignedCertificate(string subjectName) { // 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(); // 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 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); // 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 cert.NotAfter = DateTime.Now; 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(EncodingType.XCN_CRYPT_STRING_BASE64); // 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, EncodingType.XCN_CRYPT_STRING_BASE64); // instantiate the target class with the PKCS#12 data (and the empty password) return 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 ); }
public static X509Certificate2 CreateSelfSignedCertificate(string issuer, string name) { try { // create a DN for issuer and subject var dn = new CX500DistinguishedName(); dn.Encode("CN=" + issuer, X500NameFlags.XCN_CERT_NAME_STR_NONE); // create a private key for the certificate var privateKey = new CX509PrivateKey(); privateKey.ProviderName = "Microsoft Base Cryptographic Provider v1.0"; privateKey.MachineContext = true; privateKey.Length = 2048; privateKey.KeySpec = X509KeySpec.XCN_AT_SIGNATURE; 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 extended key usage (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); // create the self signing request var cert = new CX509CertificateRequestCertificate(); cert.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, privateKey, ""); cert.Issuer = dn; cert.Subject = dn; cert.NotBefore = DateTime.Now; cert.NotAfter = DateTime.Now.AddYears(1); // 1 year expiration cert.X509Extensions.Add((CX509Extension)eku); cert.HashAlgorithm = hashobj; cert.Encode(); // do the final enrollment process var enroll = new CX509Enrollment(); enroll.InitializeFromRequest(cert); enroll.CertificateFriendlyName = name; string csr = enroll.CreateRequest(); // output a base64 encoded PKCS#12 enroll.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedCertificate, csr, EncodingType.XCN_CRYPT_STRING_BASE64, ""); var base64encoded = enroll.CreatePFX("", PFXExportOptions.PFXExportChainWithRoot); // return the certificate return(new X509Certificate2(Convert.FromBase64String(base64encoded), "", X509KeyStorageFlags.Exportable)); } catch (Exception exc) { Trace.TraceError("Failed to create a self-signed certificate ({0})", exc); throw; } }
public static X509Certificate2 CreateSelfSignedCertificate(string subjectName, DateTime startDate, DateTime endDate, String password) { // Create DistinguishedName for subject and issuer var name = new CX500DistinguishedName(); name.Encode("CN=" + subjectName, X500NameFlags.XCN_CERT_NAME_STR_NONE); // Create a new Private Key for the certificate CX509PrivateKey privateKey = new CX509PrivateKey(); privateKey.ProviderName = "Microsoft RSA SChannel Cryptographic Provider"; privateKey.KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE; privateKey.Length = 2048; privateKey.SecurityDescriptor = "D:PAI(A;;0xd01f01ff;;;SY)(A;;0xd01f01ff;;;BA)(A;;0x80120089;;;NS)"; privateKey.MachineContext = true; privateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG; privateKey.Create(); // Define the hashing algorithm var serverauthoid = new CObjectId(); serverauthoid.InitializeFromValue("1.3.6.1.5.5.7.3.1"); // Server Authentication var ekuoids = new CObjectIds(); ekuoids.Add(serverauthoid); var ekuext = new CX509ExtensionEnhancedKeyUsage(); ekuext.InitializeEncode(ekuoids); // Create the self signing request var cert = new CX509CertificateRequestCertificate(); cert.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, privateKey, String.Empty); cert.Subject = name; cert.Issuer = cert.Subject; cert.NotBefore = startDate; cert.NotAfter = endDate; cert.X509Extensions.Add((CX509Extension)ekuext); cert.Encode(); // Enroll the certificate var enroll = new CX509Enrollment(); enroll.InitializeFromRequest(cert); string certData = enroll.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64HEADER); enroll.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedCertificate, certData, EncodingType.XCN_CRYPT_STRING_BASE64HEADER, String.Empty); var base64encoded = enroll.CreatePFX(password, PFXExportOptions.PFXExportChainWithRoot); // Instantiate the target class with the PKCS#12 data return(new X509Certificate2( System.Convert.FromBase64String(base64encoded), password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable)); }
protected static string GenerateCSR() { var objPrivateKey = new CX509PrivateKey(); objPrivateKey.MachineContext = false; objPrivateKey.Length = 2048; objPrivateKey.ProviderType = X509ProviderType.XCN_PROV_RSA_AES; objPrivateKey.KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE; objPrivateKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_ALL_USAGES; objPrivateKey.CspInformations = new CCspInformations(); objPrivateKey.CspInformations.AddAvailableCsps(); objPrivateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG; objPrivateKey.Create(); var cert = new CX509CertificateRequestPkcs10(); cert.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextUser, objPrivateKey, string.Empty); var objExtensionKeyUsage = new CX509ExtensionKeyUsage(); objExtensionKeyUsage.InitializeEncode((X509KeyUsageFlags)X509KeyUsageFlags.XCN_CERT_DIGITAL_SIGNATURE_KEY_USAGE | X509KeyUsageFlags.XCN_CERT_NON_REPUDIATION_KEY_USAGE | X509KeyUsageFlags.XCN_CERT_KEY_ENCIPHERMENT_KEY_USAGE | X509KeyUsageFlags.XCN_CERT_DATA_ENCIPHERMENT_KEY_USAGE ); cert.X509Extensions.Add((CX509Extension)objExtensionKeyUsage); var cobjectId = new CObjectId(); cobjectId.InitializeFromName(CERTENROLL_OBJECTID.XCN_OID_PKIX_KP_CLIENT_AUTH); var cobjectIds = new CObjectIds(); cobjectIds.Add(cobjectId); var pValue = cobjectIds; var cx509ExtensionEnhancedKeyUsage = new CX509ExtensionEnhancedKeyUsage(); cx509ExtensionEnhancedKeyUsage.InitializeEncode(pValue); cert.X509Extensions.Add((CX509Extension)cx509ExtensionEnhancedKeyUsage); var cx509Enrollment = new CX509Enrollment(); cx509Enrollment.InitializeFromRequest(cert); var output = cx509Enrollment.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64); return(output); }
private void SetEnhancedUsages() { var oids = new CObjectIds(); for (int i = 0; i < EnhancedUsages.Length; i++) { var s = EnhancedUsages[i]; var oid = new CObjectId(); var eu = Oid.FromFriendlyName(s, OidGroup.EnhancedKeyUsage); oid.InitializeFromValue(eu.Value); oids.Add(oid); } var eku = new CX509ExtensionEnhancedKeyUsage(); eku.InitializeEncode(oids); ExtensionsToAdd.Add((CX509Extension)eku); }
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 void GenerateCsr(SSLCertificate cert) { // Create all the objects that will be required CX509CertificateRequestPkcs10 pkcs10 = new CX509CertificateRequestPkcs10(); CX509PrivateKey privateKey = new CX509PrivateKey(); CCspInformation csp = new CCspInformation(); CCspInformations csPs = new CCspInformations(); CX500DistinguishedName dn = new CX500DistinguishedName(); CX509Enrollment enroll = new CX509Enrollment(); CObjectIds objectIds = new CObjectIds(); CObjectId clientObjectId = new CObjectId(); CObjectId serverObjectId = new CObjectId(); CX509ExtensionKeyUsage extensionKeyUsage = new CX509ExtensionKeyUsage(); CX509ExtensionEnhancedKeyUsage x509ExtensionEnhancedKeyUsage = new CX509ExtensionEnhancedKeyUsage(); try { // Initialize the csp object using the desired Cryptograhic Service Provider (CSP) csp.InitializeFromName("Microsoft RSA SChannel Cryptographic Provider"); // Add this CSP object to the CSP collection object csPs.Add(csp); // Provide key container name, key length and key spec to the private key object //objPrivateKey.ContainerName = "AlejaCMa"; privateKey.Length = cert.CSRLength; privateKey.KeySpec = X509KeySpec.XCN_AT_SIGNATURE; privateKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_ALL_USAGES; privateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG | X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG; privateKey.MachineContext = true; // Provide the CSP collection object (in this case containing only 1 CSP object) // to the private key object privateKey.CspInformations = csPs; // Create the actual key pair privateKey.Create(); // Initialize the PKCS#10 certificate request object based on the private key. // Using the context, indicate that this is a user certificate request and don't // provide a template name pkcs10.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, privateKey, ""); cert.PrivateKey = privateKey.ToString(); // Key Usage Extension extensionKeyUsage.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 ); pkcs10.X509Extensions.Add((CX509Extension)extensionKeyUsage); // Enhanced Key Usage Extension clientObjectId.InitializeFromValue("1.3.6.1.5.5.7.3.2"); objectIds.Add(clientObjectId); serverObjectId.InitializeFromValue("1.3.6.1.5.5.7.3.1"); objectIds.Add(serverObjectId); x509ExtensionEnhancedKeyUsage.InitializeEncode(objectIds); pkcs10.X509Extensions.Add((CX509Extension)x509ExtensionEnhancedKeyUsage); // Encode the name in using the Distinguished Name object string request = String.Format(@"CN={0}, O={1}, OU={2}, L={3}, S={4}, C={5}", cert.Hostname, cert.Organisation, cert.OrganisationUnit, cert.City, cert.State, cert.Country); dn.Encode(request, X500NameFlags.XCN_CERT_NAME_STR_NONE); // Assing the subject name by using the Distinguished Name object initialized above pkcs10.Subject = dn; // Create enrollment request enroll.InitializeFromRequest(pkcs10); enroll.CertificateFriendlyName = cert.FriendlyName; cert.CSR = enroll.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64REQUESTHEADER); } catch (Exception ex) { Log.WriteError("Error creating CSR", ex); } }
private static StoreName store = StoreName.My; // Store as a personal certificate private static X509Certificate2 CreateSelfSignedCertificate(string Operator, string SiteId, int SeqNo, bool isServerCert, string SAN) { // Create a custom subject name & friendly name string distName = $"CN={FriendlyName.ToLower()}_{SiteId}_{SeqNo}, OU={Operator}_{SiteId}, O={Operator}, C=GB"; // create DN for subject and issuer // var dn = new X500DistinguishedName(distName); // dn.Encode(distName, X500NameFlags.XCN_CERT_NAME_STR_NONE); var dn = new CX500DistinguishedName(); dn.Encode(distName, X500NameFlags.XCN_CERT_NAME_STR_NONE); // create a new private key for the certificate //CX509PrivateKey privateKey = new CX509PrivateKey(); //var privateKey = new CX509PrivateKey(); var typeName = "X509Enrollment.CX509PrivateKey"; var type = Type.GetTypeFromProgID(typeName); if (type == null) { throw new Exception(typeName + " is not available on your system: 0x80040154 (REGDB_E_CLASSNOTREG)"); } var privateKey = Activator.CreateInstance(type) as IX509PrivateKey; if (privateKey == null) { throw new Exception("Your certlib does not know an implementation of " + typeName + " (in HKLM:\\SOFTWARE\\Classes\\Interface\\)!"); } 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.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, "SHA512"); // 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 if (isServerCert) { oid.InitializeFromValue("1.3.6.1.5.5.7.3.1"); // SSL Server } else { oid.InitializeFromValue("1.3.6.1.5.5.7.3.2"); // SSL client } 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(X509CertificateEnrollmentContext.ContextMachine, privateKey, ""); if (!string.IsNullOrEmpty(SAN)) { 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, SAN); // Set Alternative Names objAlternativeNames.Add(objRfc822Name); objExtensionAlternativeNames.InitializeEncode(objAlternativeNames); cert.X509Extensions.Add((CX509Extension)objExtensionAlternativeNames); } cert.Subject = dn; cert.Issuer = dn; // the issuer and the subject are the same cert.NotBefore = DateTime.Today; cert.NotAfter = DateTime.Today.AddYears(10); // expire in 10 years time 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 = FriendlyName; // 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) X509Certificate2 newCert = new 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 // Ensure the machine key is created and retained // http://stackoverflow.com/questions/425688/how-to-set-read-permission-on-the-private-key-file-of-x-509-certificate-from-ne | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet); return(newCert); }
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]))); }
/// <summary> /// Generates a self-signed test certificate /// </summary> /// <param name="subjectName">Subject name value</param> /// <param name="password">Password for encrypting the certificate</param> /// <param name="hashAlgorithm">The hash algorithm used for generating padding bytes when encrypting the certificate</param> /// <returns>Certificate object with exportable private key</returns> public static X509Certificate2 CreateSelfSignedCertificate(string subjectName, string password, string hashAlgorithm) { // Create a DN for subject and issuer var dn = new CX500DistinguishedName(); dn.Encode("CN=" + subjectName, X500NameFlags.XCN_CERT_NAME_STR_NONE); // Create a private key for the certificate CX509PrivateKey privateKey = new CX509PrivateKey(); privateKey.ProviderName = "Microsoft RSA SChannel Cryptographic Provider"; privateKey.MachineContext = true; privateKey.Length = 2048; privateKey.KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE; privateKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_ALL_USAGES; privateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG; privateKey.Create(); // 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, hashAlgorithm); // Add extended key usage to support client and server authentication var oidlist = new CObjectIds(); // Server authentiation var oid1 = new CObjectId(); oid1.InitializeFromValue("1.3.6.1.5.5.7.3.1"); oidlist.Add(oid1); // Client authentication var oid2 = new CObjectId(); oid2.InitializeFromValue("1.3.6.1.5.5.7.3.2"); oidlist.Add(oid2); var eku = new CX509ExtensionEnhancedKeyUsage(); eku.InitializeEncode(oidlist); // Create the self signing request. This will be returned as the self-signed // certificate so we don't have to install anything in the system certificate // store (which is what happens if the enrollment object is used) var cert = new CX509CertificateRequestCertificate(); cert.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, privateKey, ""); cert.Subject = dn; cert.Issuer = dn; cert.NotBefore = DateTime.Now; cert.NotAfter = DateTime.Now.AddHours(1); cert.X509Extensions.Add((CX509Extension)eku); cert.HashAlgorithm = hashobj; cert.Encode(); // Return the certificate object X509Certificate2 newCert = new X509Certificate2( Convert.FromBase64String(cert.RawData), password, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet); return(newCert); }
public static void Main(string[] args) { string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\"; Console.WriteLine("...Self-Signing Certificate"); X509Certificate2 certificateToValidate = new X509Certificate2(); X509Store store = new X509Store("MY", StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); X509Certificate2Collection collection = store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, "CN=ATtiny13 Plant", false); store.Close(); if (collection.Count == 0) { Console.WriteLine("...Generating New Certificate"); var dn = new CX500DistinguishedName(); dn.Encode("CN=ATtiny13 Plant", X500NameFlags.XCN_CERT_NAME_STR_NONE); var privateKey = new CX509PrivateKey(); privateKey.ProviderName = "Microsoft Base Cryptographic Provider v1.0"; privateKey.MachineContext = false; //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"); var oid = new CObjectId(); oid.InitializeFromValue("1.3.6.1.5.5.7.3.3"); //eku for code signing var oidlist = new CObjectIds(); oidlist.Add(oid); var eku = new CX509ExtensionEnhancedKeyUsage(); eku.InitializeEncode(oidlist); var cert = new CX509CertificateRequestCertificate(); cert.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextUser, privateKey, ""); cert.Subject = dn; cert.Issuer = dn; cert.NotBefore = DateTime.Now; cert.NotAfter = cert.NotBefore.AddYears(5); cert.X509Extensions.Add((CX509Extension)eku); cert.HashAlgorithm = hashobj; cert.Encode(); var enroll = new CX509Enrollment(); enroll.InitializeFromRequest(cert); enroll.CertificateFriendlyName = "ATtiny13 Plant"; 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, ""); var base64encoded = enroll.CreatePFX("", PFXExportOptions.PFXExportChainWithRoot); Console.WriteLine(base64encoded); certificateToValidate = new System.Security.Cryptography.X509Certificates.X509Certificate2(System.Convert.FromBase64String(base64encoded), "", System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable); } else { foreach (X509Certificate2 x509 in collection) { certificateToValidate = x509; break; } //store.AddRange(collection); } if (IsAdministrator() == false) { Console.WriteLine("...Restart program and run as Admin"); var exeName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName; ProcessStartInfo startInfo = new ProcessStartInfo(exeName); startInfo.Verb = "runas"; System.Diagnostics.Process.Start(startInfo); Environment.Exit(0); //Application.Current.Shutdown(); } Console.WriteLine("...Installing Certificate"); store = new X509Store(StoreName.Root, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadWrite); store.Add(certificateToValidate); store.Close(); store = new X509Store(StoreName.TrustedPublisher, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadWrite); store.Add(certificateToValidate); store.Close(); byte[] certBytes = certificateToValidate.Export(X509ContentType.Cert, ""); //X509ContentType.Authenticode System.IO.File.WriteAllBytes(path + "usbtiny.cer", certBytes); Console.WriteLine("...Driver Signing and Time Stamping"); ProcessStartInfo start = new ProcessStartInfo(); start.FileName = "self-sign.exe"; using (Process proc = Process.Start(start)) { proc.WaitForExit(); } Console.WriteLine("...Installing Driver"); start = new ProcessStartInfo(); start.FileName = "pnputil"; start.Arguments = "-a \"" + path + "usbtiny.inf\""; using (Process proc = Process.Start(start)) { proc.WaitForExit(); } start.FileName = "InfDefaultInstall"; start.Arguments = "\"" + path + "usbtiny.inf\""; using (Process proc = Process.Start(start)) { proc.WaitForExit(); } }
// 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 string CreateRequest(string cn, string ou, string o, string l, string s, string c, string oid, int keyLength) { var csp = new CCspInformations(); csp.AddAvailableCsps(); var privateKey = (IX509PrivateKey)Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509PrivateKey")); privateKey.Length = keyLength; privateKey.KeySpec = X509KeySpec.XCN_AT_SIGNATURE; privateKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_ALL_USAGES; privateKey.MachineContext = false; privateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG; privateKey.CspInformations = csp; privateKey.Create(); var pkcs10 = (CX509CertificateRequestPkcs10) Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509CertificateRequestPkcs10")); pkcs10.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextUser, privateKey, string.Empty); var extensionKeyUsage = (CX509ExtensionKeyUsage) Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509ExtensionKeyUsage")); extensionKeyUsage.InitializeEncode(X509KeyUsageFlags.XCN_CERT_DIGITAL_SIGNATURE_KEY_USAGE | X509KeyUsageFlags.XCN_CERT_NON_REPUDIATION_KEY_USAGE | X509KeyUsageFlags.XCN_CERT_KEY_ENCIPHERMENT_KEY_USAGE | X509KeyUsageFlags.XCN_CERT_DATA_ENCIPHERMENT_KEY_USAGE); pkcs10.X509Extensions.Add((CX509Extension)extensionKeyUsage); var objectId = new CObjectId(); var objectIds = new CObjectIds(); var extensionEnhancedKeyUsage = (CX509ExtensionEnhancedKeyUsage) Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509ExtensionEnhancedKeyUsage")); objectId.InitializeFromValue(oid); objectIds.Add(objectId); extensionEnhancedKeyUsage.InitializeEncode(objectIds); pkcs10.X509Extensions.Add((CX509Extension)extensionEnhancedKeyUsage); var san = GetSAN(cn); pkcs10.X509Extensions.Add((CX509Extension)san); var distinguishedName = (CX500DistinguishedName) Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX500DistinguishedName")); cn = ConvertCn(cn); var subjectName = $"{cn},OU = {ou},O = {o} ,L = {l},S = {s},C = {c}"; distinguishedName.Encode(subjectName); pkcs10.Subject = distinguishedName; var enroll = (CX509Enrollment)Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509Enrollment")); enroll.InitializeFromRequest(pkcs10); var request = enroll.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64HEADER); return(request); }
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); }
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 void GenerateCsr(SSLCertificate cert) { // Create all the objects that will be required CX509CertificateRequestPkcs10 pkcs10 = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509CertificateRequestPkcs10", true)) as CX509CertificateRequestPkcs10; CX509PrivateKey privateKey = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509PrivateKey", true)) as CX509PrivateKey; CCspInformation csp = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CCspInformation", true)) as CCspInformation; CCspInformations csPs = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CCspInformations", true)) as CCspInformations; CX500DistinguishedName dn = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX500DistinguishedName", true)) as CX500DistinguishedName; CX509Enrollment enroll = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509Enrollment", true)) as CX509Enrollment; CObjectIds objectIds = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CObjectIds", true)) as CObjectIds; CObjectId objectId = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CObjectId", true)) as CObjectId; CX509ExtensionKeyUsage extensionKeyUsage = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509ExtensionKeyUsage", true)) as CX509ExtensionKeyUsage; CX509ExtensionEnhancedKeyUsage x509ExtensionEnhancedKeyUsage = Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509ExtensionEnhancedKeyUsage", true)) as CX509ExtensionEnhancedKeyUsage; try { // Initialize the csp object using the desired Cryptograhic Service Provider (CSP) csp.InitializeFromName("Microsoft RSA SChannel Cryptographic Provider"); // Add this CSP object to the CSP collection object csPs.Add(csp); // Provide key container name, key length and key spec to the private key object privateKey.Length = cert.CSRLength; privateKey.KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE; privateKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_ALL_USAGES; privateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG | X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_ARCHIVING_FLAG | X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_PLAINTEXT_ARCHIVING_FLAG | X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG; privateKey.MachineContext = true; // Provide the CSP collection object (in this case containing only 1 CSP object) // to the private key object privateKey.CspInformations = csPs; // Create the actual key pair privateKey.Create(); // Initialize the PKCS#10 certificate request object based on the private key. // Using the context, indicate that this is a user certificate request and don't // provide a template name pkcs10.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, privateKey, ""); cert.PrivateKey = privateKey.ToString(); // Key Usage Extension extensionKeyUsage.InitializeEncode( CertEnrollInterop.X509KeyUsageFlags.XCN_CERT_DIGITAL_SIGNATURE_KEY_USAGE | CertEnrollInterop.X509KeyUsageFlags.XCN_CERT_NON_REPUDIATION_KEY_USAGE | CertEnrollInterop.X509KeyUsageFlags.XCN_CERT_KEY_ENCIPHERMENT_KEY_USAGE | CertEnrollInterop.X509KeyUsageFlags.XCN_CERT_DATA_ENCIPHERMENT_KEY_USAGE ); pkcs10.X509Extensions.Add((CX509Extension)extensionKeyUsage); // Enhanced Key Usage Extension objectId.InitializeFromName(CertEnrollInterop.CERTENROLL_OBJECTID.XCN_OID_PKIX_KP_SERVER_AUTH); objectIds.Add(objectId); x509ExtensionEnhancedKeyUsage.InitializeEncode(objectIds); pkcs10.X509Extensions.Add((CX509Extension)x509ExtensionEnhancedKeyUsage); // Encode the name in using the Distinguished Name object string request = String.Format(@"CN={0}, O={1}, OU={2}, L={3}, S={4}, C={5}", cert.Hostname, cert.Organisation, cert.OrganisationUnit, cert.City, cert.State, cert.Country); dn.Encode(request, X500NameFlags.XCN_CERT_NAME_STR_NONE); // enable SMIME capabilities pkcs10.SmimeCapabilities = true; // Assing the subject name by using the Distinguished Name object initialized above pkcs10.Subject = dn; // Create enrollment request enroll.InitializeFromRequest(pkcs10); enroll.CertificateFriendlyName = cert.FriendlyName; cert.CSR = enroll.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64REQUESTHEADER); } catch (Exception ex) { Log.WriteError("Error creating CSR", ex); } }
/// <summary> /// Create a certificate signing request. /// </summary> /// <param name="subjectName">The subject name of the certificate.</param> /// <param name="keyLength">Size of the key in bits.</param> /// <param name="durationYears">Duration of the certificate, specified in years.</param> /// <param name="oids">Collection of OIDs identifying certificate usage.</param> public static CX509CertificateRequestCertificate CreateCertificateSigningRequest(string subjectName, int keyLength, int durationYears, List<string> oids) { // Prepend the subject name with CN= if it doesn't begin with CN=, E=, etc.. if (subjectName.IndexOf("=") < 0) subjectName = "CN=" + subjectName; // Generate a distinguished name. CX500DistinguishedName distinguishedName = new CX500DistinguishedName(); distinguishedName.Encode(subjectName, X500NameFlags.XCN_CERT_NAME_STR_NONE); // Generate a private key. CX509PrivateKey privateKey = new CX509PrivateKey(); privateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG; privateKey.KeySpec = X509KeySpec.XCN_AT_SIGNATURE; privateKey.Length = keyLength; privateKey.MachineContext = true; privateKey.ProviderName = "Microsoft Enhanced Cryptographic Provider v1.0"; privateKey.Create(); // Use the SHA-512 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, "SHA512"); // Load the OIDs passed in and specify enhanced key usages. CObjectIds oidCollection = new CObjectIds(); foreach (string oidID in oids) { CObjectId oid = new CObjectId(); oid.InitializeFromValue(oidID); oidCollection.Add(oid); } CX509ExtensionKeyUsage keyUsage = new CX509ExtensionKeyUsage(); keyUsage.InitializeEncode(CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_DIGITAL_SIGNATURE_KEY_USAGE | CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_KEY_ENCIPHERMENT_KEY_USAGE); CX509ExtensionEnhancedKeyUsage enhancedKeyUsages = new CX509ExtensionEnhancedKeyUsage(); enhancedKeyUsages.InitializeEncode(oidCollection); string sanSubjectName = subjectName.Substring(subjectName.IndexOf("=") + 1); CAlternativeName sanAlternateName = new CAlternativeName(); sanAlternateName.InitializeFromString(AlternativeNameType.XCN_CERT_ALT_NAME_RFC822_NAME, sanSubjectName); CAlternativeNames sanAlternativeNames = new CAlternativeNames(); sanAlternativeNames.Add(sanAlternateName); CX509ExtensionAlternativeNames alternativeNamesExtension = new CX509ExtensionAlternativeNames(); alternativeNamesExtension.InitializeEncode(sanAlternativeNames); CX509ExtensionSmimeCapabilities smimeCapabilities = new CX509ExtensionSmimeCapabilities(); smimeCapabilities.SmimeCapabilities.AddAvailableSmimeCapabilities(false); // Create the self-signing request. CX509CertificateRequestCertificate cert = new CX509CertificateRequestCertificate(); cert.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, privateKey, ""); cert.Subject = distinguishedName; cert.Issuer = distinguishedName; cert.NotBefore = DateTime.Now; cert.NotAfter = DateTime.Now.AddYears(1); cert.X509Extensions.Add((CX509Extension)keyUsage); cert.X509Extensions.Add((CX509Extension)enhancedKeyUsages); cert.X509Extensions.Add((CX509Extension)alternativeNamesExtension); cert.X509Extensions.Add((CX509Extension)smimeCapabilities); cert.HashAlgorithm = hashAlgorithm; cert.Encode(); return cert; }
/// <summary> /// Add Reference: COM > TypeLibraries > CertEnroll 1.0 Type Library /// </summary> /// <param name="subjectName"></param> /// <returns></returns> public static X509Certificate2 CreateSelfSignedCertificate(string subjectName, TimeSpan expiresIn) { // 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(); // 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 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); // 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 cert.NotAfter = DateTime.Now.Add(expiresIn); 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); // instantiate the target class with the PKCS#12 data (and the empty password) return(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 )); }
/// <summary> /// Function used to create a certificate signing request using the OS. /// Note that this function will place a certificate in the "Certificate Enrollment Requests" folder /// of the certificate store specified in loc. You can view this by running either /// certmgr or mmc from the command line. /// </summary> /// <param name="loc">Location to put certificate</param> /// <param name="subject_line">The subject line of the certificate, fields should be ; seperated, i.e.: "C=US; ST=Minnesota; L=Eden Prairie; O=Forward Pay Systems, Inc.; OU=Forward Pay; CN=fps.com"</param> /// <returns>The certificate signing request, if successful in PEM format</returns> public string GenerateRequest() { //code originally came from: http://blogs.msdn.com/b/alejacma/archive/2008/09/05/how-to-create-a-certificate-request-with-certenroll-and-net-c.aspx //modified version of it is here: http://stackoverflow.com/questions/16755634/issue-generating-a-csr-in-windows-vista-cx509certificaterequestpkcs10 //here is the standard for certificates: http://www.ietf.org/rfc/rfc3280.txt //the PKCS#10 certificate request (http://msdn.microsoft.com/en-us/library/windows/desktop/aa377505.aspx) CX509CertificateRequestPkcs10 objPkcs10 = new CX509CertificateRequestPkcs10(); //assymetric private key that can be used for encryption (http://msdn.microsoft.com/en-us/library/windows/desktop/aa378921.aspx) CX509PrivateKey objPrivateKey = new CX509PrivateKey(); //access to the general information about a cryptographic provider (http://msdn.microsoft.com/en-us/library/windows/desktop/aa375967.aspx) CCspInformation objCSP = new CCspInformation(); //collection on cryptographic providers available: http://msdn.microsoft.com/en-us/library/windows/desktop/aa375967(v=vs.85).aspx CCspInformations objCSPs = new CCspInformations(); CX500DistinguishedName objDN = new CX500DistinguishedName(); //top level object that enables installing a certificate response http://msdn.microsoft.com/en-us/library/windows/desktop/aa377809.aspx CX509Enrollment objEnroll = new CX509Enrollment(); CObjectIds objObjectIds = new CObjectIds(); CObjectId objObjectId = new CObjectId(); CObjectId objObjectId2 = new CObjectId(); CX509ExtensionKeyUsage objExtensionKeyUsage = new CX509ExtensionKeyUsage(); CX509ExtensionEnhancedKeyUsage objX509ExtensionEnhancedKeyUsage = new CX509ExtensionEnhancedKeyUsage(); string csr_pem = null; // Initialize the csp object using the desired Cryptograhic Service Provider (CSP) objCSPs.AddAvailableCsps(); //Provide key container name, key length and key spec to the private key object objPrivateKey.ProviderName = providerName; objPrivateKey.Length = KeyLength; objPrivateKey.KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE; //Must flag as XCN_AT_KEYEXCHANGE to use this certificate for exchanging symmetric keys (needed for most SSL cipher suites) objPrivateKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_ALL_USAGES; if (Location == StoreLocation.LocalMachine) { objPrivateKey.MachineContext = true; } else { objPrivateKey.MachineContext = false; //must set this to true if installing to the local machine certificate store } objPrivateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG; //must set this if we want to be able to export it later. (for WinSIP maybe we don't want to be able to ever export the key??) objPrivateKey.CspInformations = objCSPs; // Create the actual key pair objPrivateKey.Create(); // Initialize the PKCS#10 certificate request object based on the private key. // Using the context, indicate that this is a user certificate request and don't // provide a template name if (Location == StoreLocation.LocalMachine) { objPkcs10.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, objPrivateKey, ""); } else { objPkcs10.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextUser, objPrivateKey, ""); } //Set has to sha256 CObjectId hashobj = new CObjectId(); hashobj.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID, ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY, AlgorithmFlags.AlgorithmFlagsNone, "SHA256"); objPkcs10.HashAlgorithm = hashobj; // Key Usage Extension -- we only need digital signature and key encipherment for TLS: // NOTE: in openSSL, I didn't used to request any specific extensions. Instead, I let the CA add them objExtensionKeyUsage.InitializeEncode( CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_DIGITAL_SIGNATURE_KEY_USAGE | CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_KEY_ENCIPHERMENT_KEY_USAGE ); objPkcs10.X509Extensions.Add((CX509Extension)objExtensionKeyUsage); // Enhanced Key Usage Extension objObjectId.InitializeFromValue("1.3.6.1.5.5.7.3.1"); // OID for Server Authentication usage (see this: http://stackoverflow.com/questions/17477279/client-authentication-1-3-6-1-5-5-7-3-2-oid-in-server-certificates) objObjectId2.InitializeFromValue("1.3.6.1.5.5.7.3.2"); // OID for Client Authentication usage (see this: http://stackoverflow.com/questions/17477279/client-authentication-1-3-6-1-5-5-7-3-2-oid-in-server-certificates) objObjectIds.Add(objObjectId); objObjectIds.Add(objObjectId2); objX509ExtensionEnhancedKeyUsage.InitializeEncode(objObjectIds); objPkcs10.X509Extensions.Add((CX509Extension)objX509ExtensionEnhancedKeyUsage); // Encode the name in using the Distinguished Name object // see here: http://msdn.microsoft.com/en-us/library/windows/desktop/aa379394(v=vs.85).aspx /*objDN.Encode( * "C=US, ST=Minnesota, L=Eden Prairie, O=Forward Pay Systems; Inc., OU=Forward Pay, CN=ERIC_CN", * X500NameFlags.XCN_CERT_NAME_STR_NONE * );*/ objDN.Encode( Subject, X500NameFlags.XCN_CERT_NAME_STR_SEMICOLON_FLAG ); //"C=US; ST=Minnesota; L=Eden Prairie; O=Forward Pay Systems, Inc.; OU=Forward Pay; CN=ERIC_CN" // Assing the subject name by using the Distinguished Name object initialized above objPkcs10.Subject = objDN; //suppress extra attributes: objPkcs10.SuppressDefaults = true; // Create enrollment request objEnroll.InitializeFromRequest(objPkcs10); csr_pem = objEnroll.CreateRequest( EncodingType.XCN_CRYPT_STRING_BASE64 ); csr_pem = "-----BEGIN CERTIFICATE REQUEST-----\r\n" + csr_pem + "-----END CERTIFICATE REQUEST-----"; return(csr_pem); }
/// <summary> /// Create a certificate signing request. /// </summary> /// <param name="subjectName">The subject name of the certificate.</param> /// <param name="keyLength">Size of the key in bits.</param> /// <param name="durationYears">Duration of the certificate, specified in years.</param> /// <param name="oids">Collection of OIDs identifying certificate usage.</param> public static CX509CertificateRequestCertificate CreateCertificateSigningRequest(string subjectName, int keyLength, int durationYears, List <string> oids) { // Prepend the subject name with CN= if it doesn't begin with CN=, E=, etc.. if (subjectName.IndexOf("=") < 0) { subjectName = "CN=" + subjectName; } // Generate a distinguished name. CX500DistinguishedName distinguishedName = new CX500DistinguishedName(); distinguishedName.Encode(subjectName, X500NameFlags.XCN_CERT_NAME_STR_NONE); // Generate a private key. CX509PrivateKey privateKey = new CX509PrivateKey(); privateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG; privateKey.KeySpec = X509KeySpec.XCN_AT_SIGNATURE; privateKey.Length = keyLength; privateKey.MachineContext = true; privateKey.ProviderName = "Microsoft Enhanced Cryptographic Provider v1.0"; privateKey.Create(); // Use the SHA-512 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, "SHA512"); // Load the OIDs passed in and specify enhanced key usages. CObjectIds oidCollection = new CObjectIds(); foreach (string oidID in oids) { CObjectId oid = new CObjectId(); oid.InitializeFromValue(oidID); oidCollection.Add(oid); } CX509ExtensionKeyUsage keyUsage = new CX509ExtensionKeyUsage(); keyUsage.InitializeEncode(CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_DIGITAL_SIGNATURE_KEY_USAGE | CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_KEY_ENCIPHERMENT_KEY_USAGE); CX509ExtensionEnhancedKeyUsage enhancedKeyUsages = new CX509ExtensionEnhancedKeyUsage(); enhancedKeyUsages.InitializeEncode(oidCollection); string sanSubjectName = subjectName.Substring(subjectName.IndexOf("=") + 1); CAlternativeName sanAlternateName = new CAlternativeName(); sanAlternateName.InitializeFromString(AlternativeNameType.XCN_CERT_ALT_NAME_RFC822_NAME, sanSubjectName); CAlternativeNames sanAlternativeNames = new CAlternativeNames(); sanAlternativeNames.Add(sanAlternateName); CX509ExtensionAlternativeNames alternativeNamesExtension = new CX509ExtensionAlternativeNames(); alternativeNamesExtension.InitializeEncode(sanAlternativeNames); CX509ExtensionSmimeCapabilities smimeCapabilities = new CX509ExtensionSmimeCapabilities(); smimeCapabilities.SmimeCapabilities.AddAvailableSmimeCapabilities(false); // Create the self-signing request. CX509CertificateRequestCertificate cert = new CX509CertificateRequestCertificate(); cert.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, privateKey, ""); cert.Subject = distinguishedName; cert.Issuer = distinguishedName; cert.NotBefore = DateTime.Now; cert.NotAfter = DateTime.Now.AddYears(1); cert.X509Extensions.Add((CX509Extension)keyUsage); cert.X509Extensions.Add((CX509Extension)enhancedKeyUsages); cert.X509Extensions.Add((CX509Extension)alternativeNamesExtension); cert.X509Extensions.Add((CX509Extension)smimeCapabilities); cert.HashAlgorithm = hashAlgorithm; cert.Encode(); return(cert); }
public static X509Certificate2 CreateSelfSignedCertificateOldImplementationNetFramework( string subjectName, string friendlyName, ILoggerInterface logger, int expirationDays = 90) { // create DN for subject var dn = new CX500DistinguishedName(); dn.Encode("CN=" + subjectName, X500NameFlags.XCN_CERT_NAME_STR_NONE); // create DN for the issuer var issuer = new CX500DistinguishedName(); issuer.Encode("CN=ChefCertificate", 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(); // 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 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); // Create the self signing request var cert = new CX509CertificateRequestCertificate(); cert.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, privateKey, string.Empty); cert.Subject = dn; cert.Issuer = issuer; cert.NotBefore = DateTime.Now; // this cert expires immediately. Change to whatever makes sense for you cert.NotAfter = DateTime.Now.AddDays(expirationDays); 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 = friendlyName; // 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, string.Empty); // no password // output a base64 encoded PKCS#12 so we can import it back to the .Net security classes var base64Encoded = enroll.CreatePFX( string.Empty, // no password, this is for internal consumption PFXExportOptions.PFXExportChainWithRoot); // Delete the key var storePath = UtilsCertificate.FindKeyStoragePath(privateKey.UniqueContainerName); if (string.IsNullOrWhiteSpace(storePath)) { logger.LogWarning(false, $"Unable to determine private key store path for key with UCN '{privateKey.UniqueContainerName}', keys will build up in disk storage."); } else { File.Delete(storePath); } // instantiate the target class with the PKCS#12 data (and the empty password) var crt = new X509Certificate2( Convert.FromBase64String(base64Encoded), string.Empty, // mark the private key as exportable (this is usually what you want to do) X509KeyStorageFlags.EphemeralKeySet | X509KeyStorageFlags.Exportable); // Remove the locally signed certificate from the local store, as we are only interested in // the exported PFX file UtilsCertificate.RemoveCertificateFromLocalStoreByThumbprint(crt.Thumbprint); return(crt); }
/// <summary> /// CreateSelfSignedCertificate method implementation /// </summary> private static string InternalCreateSelfSignedCertificate(string subjectName, int years) { var dn = new CX500DistinguishedName(); var neos = new CX500DistinguishedName(); dn.Encode("CN=" + subjectName, X500NameFlags.XCN_CERT_NAME_STR_NONE); neos.Encode("CN=MFA RSA Keys Certificate", X500NameFlags.XCN_CERT_NAME_STR_NONE); CX509PrivateKey privateKey = new CX509PrivateKey(); privateKey.ProviderName = "Microsoft RSA SChannel Cryptographic Provider"; privateKey.MachineContext = true; privateKey.Length = 2048; privateKey.KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE; // use is not limited privateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG | X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG | X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_ARCHIVING_FLAG | X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_PLAINTEXT_ARCHIVING_FLAG; privateKey.SecurityDescriptor = "D:PAI(A;;0xd01f01ff;;;SY)(A;;0xd01f01ff;;;BA)(A;;0x80120089;;;NS)"; 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"); 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 coid = new CObjectId(); coid.InitializeFromValue("1.3.6.1.5.5.7.3.2"); // Client auth oidlist.Add(coid); var eku = new CX509ExtensionEnhancedKeyUsage(); eku.InitializeEncode(oidlist); // Create the self signing request var cert = new CX509CertificateRequestCertificate(); cert.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextAdministratorForceMachine, privateKey, ""); cert.Subject = dn; cert.Issuer = neos; cert.NotBefore = DateTime.Now.AddDays(-10); cert.NotAfter = DateTime.Now.AddYears(years); 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("", PFXExportOptions.PFXExportChainWithRoot); return(base64encoded); }
private static string InternalCreateSQLCertificate(string subjectName, int years, string pwd = "") { string base64encoded = string.Empty; CX500DistinguishedName dn = new CX500DistinguishedName(); CX500DistinguishedName neos = new CX500DistinguishedName(); dn.Encode("CN=" + subjectName + " " + DateTime.UtcNow.ToString("G") + " GMT", X500NameFlags.XCN_CERT_NAME_STR_NONE); neos.Encode("CN=Always Encrypted Certificate", X500NameFlags.XCN_CERT_NAME_STR_NONE); CX509PrivateKey privateKey = new CX509PrivateKey { ProviderName = "Microsoft RSA SChannel Cryptographic Provider", MachineContext = true, Length = 2048, KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE, // use is not limited ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG, SecurityDescriptor = "D:PAI(A;;0xd01f01ff;;;SY)(A;;0xd01f01ff;;;BA)(A;;0xd01f01ff;;;CO)" }; if (!string.IsNullOrEmpty(ADFSServiceSID)) { privateKey.SecurityDescriptor += "(A;;FA;;;" + ADFSServiceSID + ")"; } if (!string.IsNullOrEmpty(ADFSAccountSID)) { privateKey.SecurityDescriptor += "(A;;FA;;;" + ADFSAccountSID + ")"; } if (!string.IsNullOrEmpty(ADFSAdminGroupSID)) { privateKey.SecurityDescriptor += "(A;;FA;;;" + ADFSAdminGroupSID + ")"; } try { privateKey.Create(); CObjectId hashobj = new CObjectId(); hashobj.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID, ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY, AlgorithmFlags.AlgorithmFlagsNone, "SHA256"); // 2.5.29.37 – Enhanced Key Usage includes CObjectId oid = new CObjectId(); oid.InitializeFromValue("1.3.6.1.5.5.8.2.2"); // IP security IKE intermediate var oidlist = new CObjectIds { oid }; CObjectId coid = new CObjectId(); coid.InitializeFromValue("1.3.6.1.4.1.311.10.3.11"); // Key Recovery oidlist.Add(coid); CX509ExtensionEnhancedKeyUsage eku = new CX509ExtensionEnhancedKeyUsage(); eku.InitializeEncode(oidlist); // Create the self signing request CX509CertificateRequestCertificate certreq = new CX509CertificateRequestCertificate(); certreq.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextMachine, privateKey, ""); certreq.Subject = dn; certreq.Issuer = neos; certreq.NotBefore = DateTime.Now.AddDays(-10); certreq.NotAfter = DateTime.Now.AddYears(years); certreq.X509Extensions.Add((CX509Extension)eku); // add the EKU certreq.HashAlgorithm = hashobj; // Specify the hashing algorithm certreq.Encode(); // encode the certificate // Do the final enrollment process CX509Enrollment enroll = new CX509Enrollment(); enroll.InitializeFromRequest(certreq); // 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, ""); // output a base64 encoded PKCS#12 so we can import it back to the .Net security classes base64encoded = enroll.CreatePFX("", PFXExportOptions.PFXExportChainWithRoot); } catch (Exception ex) { privateKey.Delete(); throw ex; } finally { // DO nothing, certificate Key is stored in the system } return(base64encoded); }