private CCspInformations GetCspInformation(WindowsApi api)
        {
            CCspInformations cspList = new CCspInformations();
            CCspInformation  csp     = new CCspInformation();

            csp.InitializeFromName(GetWindowsApiProviderName(api));
            cspList.Add(csp);
            return(cspList);
        }
        /// <summary>
        /// Creates a certificate request with the given name.
        /// </summary>
        /// <param name="name"></param>
        public void CreateCertificateRequest(String name)
        {
            try
            {
                // Initialize cryptographic provider
                objCSP.InitializeFromName(this.CryptographicProviderName);
                objCSPs.Add(objCSP);

                // Set CX509PrivateKey values and create
                objPrivateKey.CspInformations = objCSPs;
                objPrivateKey.Length          = this.KeySize;
                objPrivateKey.KeySpec         = this.KeySpec;
                objPrivateKey.KeyUsage        = this.KeyUsage;
                objPrivateKey.MachineContext  = this.MachineContext;
                objPrivateKey.ExportPolicy    = this.ExportPolicy;
                objPrivateKey.Create();

                // Initalize CX509CertificateRequestCertificate.
                objCertRequest.InitializeFromPrivateKey(this.EnrollmentContextMachine, objPrivateKey, "");

                objObjectId.InitializeFromAlgorithmName(this.ObjectIdGroupId,
                                                        this.ObjectIdPublicKeyFlags,
                                                        this.AlgorithmFlags, this.AlgorithmName);

                // Add the name passed in
                objDN.Encode(
                    "CN=" + name,
                    X500NameFlags.XCN_CERT_NAME_STR_NONE
                    );

                objCertRequest.Subject       = objDN;
                objCertRequest.Issuer        = objDN;
                objCertRequest.HashAlgorithm = objObjectId;

                objCertRequest.NotBefore = DateTime.Now;
                objCertRequest.NotAfter  = DateTime.Now + (DateTime.Now.Date.AddDays(this.ExpirationLengthInDays) - DateTime.Now.Date);

                objEnroll.InitializeFromRequest(objCertRequest);
                objEnroll.CertificateFriendlyName = this.FriendlyName;
                stringResponse = objEnroll.CreateRequest(this.EncodingType);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 3
0
        // create the certifcate request
        public string CreateCertifcate(string hostName)
        {
            //  Create all the objects that will be required
            CX509CertificateRequestPkcs10 objPkcs10 = new CX509CertificateRequestPkcs10();
            CX509PrivateKey        objPrivateKey    = new CX509PrivateKey();
            CCspInformation        objCSP           = new CCspInformation();
            CCspInformations       objCSPs          = new CCspInformations();
            CX500DistinguishedName objDN            = new CX500DistinguishedName();
            CX509Enrollment        objEnroll        = new CX509Enrollment();
            CObjectIds             objObjectIds     = new CObjectIds();
            CObjectId objObjectId = new CObjectId();
            CX509ExtensionKeyUsage         objExtensionKeyUsage             = new CX509ExtensionKeyUsage();
            CX509ExtensionEnhancedKeyUsage objX509ExtensionEnhancedKeyUsage = new CX509ExtensionEnhancedKeyUsage();
            string CertifcateStr;

            try
            {
                Database db = new Database();
                /*Check if there is allready request for the hostname so we dont need to create new one*/

                if (db.CheckIfCertificateExists(hostName) == 1)
                {
                    return("Exsits");
                }

                if (db.CheckIfCertificateExists(hostName) == 2)
                {
                    return("Issued");
                }

                //create the private key (CX509CertificateRequestPkcs10 will initilizae from the private key)
                objCSP.InitializeFromName("Microsoft Enhanced Cryptographic Provider v1.0");
                objCSPs.Add(objCSP);
                objPrivateKey.Length          = 1024;
                objPrivateKey.KeySpec         = X509KeySpec.XCN_AT_SIGNATURE;
                objPrivateKey.KeyUsage        = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_ALL_USAGES;
                objPrivateKey.MachineContext  = false;
                objPrivateKey.CspInformations = objCSPs;
                objPrivateKey.Create();


                //create  pkc10 object from the privaet key
                objPkcs10.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextUser, objPrivateKey, "");
                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);

                // objPkcs10.X509Extensions.Add((CX509Extension)objExtensionKeyUsage);
                // objObjectId.InitializeFromValue("1.3.6.1.5.5.7.3.2");
                // objObjectIds.Add(objObjectId);

                //  objX509ExtensionEnhancedKeyUsage.InitializeEncode(objObjectIds);
                // objPkcs10.X509Extensions.Add((CX509Extension)objX509ExtensionEnhancedKeyUsage);

                objDN.Encode("CN=" + hostName, X500NameFlags.XCN_CERT_NAME_STR_NONE);          //create DistinguishedName
                objPkcs10.Subject = objDN;                                                     //initial the  DistinguishedName
                objEnroll.InitializeFromRequest(objPkcs10);                                    //init enrollement request
                CertifcateStr = objEnroll.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64); //Certifcate  Request
                return(CertifcateStr);
            }
            catch (Exception ex)
            {
                Database db = new Database();
                db.InsertToErrorMessageTable(hostName, 0, ex.Message, "CreateCertifcate");//insert Error Message into The Error Table Log In The DataBase
                return("Error" + ex.Message);
            }
        }
Ejemplo n.º 4
0
        public static X509Certificate2 CreateSelfSignedCertificate(string subjectName)
        {
            var distinguishedName = new CX500DistinguishedName();

            distinguishedName.Encode(
                "CN=" + subjectName,
                X500NameFlags.XCN_CERT_NAME_STR_NONE);

            CCspInformations objCSPs = new CCspInformations();
            CCspInformation  objCSP  = new CCspInformation();

            objCSP.InitializeFromName(
                "Microsoft Enhanced RSA and AES Cryptographic Provider");

            objCSPs.Add(objCSP);

            // Build the private key
            CX509PrivateKey privateKey = new CX509PrivateKey();

            privateKey.MachineContext  = false;
            privateKey.Length          = 2048;
            privateKey.CspInformations = objCSPs;
            privateKey.KeySpec         = X509KeySpec.XCN_AT_KEYEXCHANGE;
            privateKey.KeyUsage        = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_ALL_USAGES;
            privateKey.ExportPolicy    = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG;

            // Create the private key in the CSP's protected storage
            privateKey.Create();

            // Build the algorithm identifier
            var hashobj = new CObjectId();

            hashobj.InitializeFromAlgorithmName(
                ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID,
                ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY,
                AlgorithmFlags.AlgorithmFlagsNone,
                "SHA256");

            // Create the self-signing request from the private key
            var certificateRequest = new CX509CertificateRequestCertificate();

            certificateRequest.InitializeFromPrivateKey(
                X509CertificateEnrollmentContext.ContextUser,
                privateKey,
                string.Empty);

            certificateRequest.Subject       = distinguishedName;
            certificateRequest.Issuer        = distinguishedName;
            certificateRequest.NotBefore     = DateTime.Now.AddDays(-1);
            certificateRequest.NotAfter      = DateTime.Now.AddYears(100);
            certificateRequest.HashAlgorithm = hashobj;

            certificateRequest.Encode();

            var enrollment = new CX509Enrollment();

            // Load the certificate request
            enrollment.InitializeFromRequest(certificateRequest);
            enrollment.CertificateFriendlyName = subjectName;

            // Output the request in base64 and install it back as the response
            string csr = enrollment.CreateRequest();

            // Install the response
            enrollment.InstallResponse(
                InstallResponseRestrictionFlags.AllowUntrustedCertificate,
                csr,
                EncodingType.XCN_CRYPT_STRING_BASE64,
                string.Empty);

            // Get the new certificate without the private key
            byte[] certificateData = Convert.FromBase64String(enrollment.Certificate);

            return(new X509Certificate2(certificateData));
        }
Ejemplo n.º 5
0
        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);
            }
        }
Ejemplo n.º 6
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);
            }
        }
Ejemplo n.º 7
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);
			}
		}