static void Main()
        {
            //  Create all the objects that will be required
            CX509CertificateRequestPkcs10 p10 = new CX509CertificateRequestPkcs10Class();
            CX509PrivateKey pri = new CX509PrivateKeyClass();
            CX500DistinguishedName dn = new CX500DistinguishedNameClass();
            CObjectId objecc = new CObjectIdClass();
            CObjectId objhash = new CObjectId();

            string base64p10;

            //  Initialize the object ID class for the ECC algorithm (ECDSA_P256)
            //            objecc.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_PUBKEY_ALG_OID_GROUP_ID, ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY, "ECDSA_P256");
            objecc.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_PUBKEY_ALG_OID_GROUP_ID, ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY, AlgorithmFlags.AlgorithmFlagsNone, "ECDSA_P256");

            //  Initialize the object ID class for the hashing algorithm (SHA384)
            objhash.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID, ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY, AlgorithmFlags.AlgorithmFlagsNone, "SHA384");

                //  Provide provider name and the object id to the private key object
            pri.ProviderName = "Microsoft Software Key Storage Provider";
            pri.Algorithm = objecc;

                //  Create the actual key pair
            pri.Create();

                //  Encode the name in using the Distinguished Name object
            dn.Encode("CN=YourName", X500NameFlags.XCN_CERT_NAME_STR_NONE);

                //  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
            p10.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextUser, pri, "");

                //  The newly created certificate request object will contain some default extensions.
                //  Suppress these defaults by setting the SuppressDefaults flag
            p10.SuppressDefaults = true;

            p10.HashAlgorithm = objhash;

                //  Assing the subject name by using the Distinguished Name object initialized above
            p10.Subject = dn;

                //  Encode the certificate request
            p10.Encode();

                //  Get the certificate request in form of a base 64 encoded string
            base64p10 = p10.get_RawData(EncodingType.XCN_CRYPT_STRING_BASE64);

                //  print the certificate request on the console
            Console.Write(base64p10);
            Console.ReadKey();

            return;
        }
        static void Main()
        {
            //  Create all the objects that will be required
            CX509CertificateRequestPkcs10 p10 = new CX509CertificateRequestPkcs10Class();
            CX509PrivateKey        pri        = new CX509PrivateKeyClass();
            CX500DistinguishedName dn         = new CX500DistinguishedNameClass();
            CObjectId objecc  = new CObjectIdClass();
            CObjectId objhash = new CObjectId();

            string base64p10;

            //  Initialize the object ID class for the ECC algorithm (ECDSA_P256)
//            objecc.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_PUBKEY_ALG_OID_GROUP_ID, ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY, "ECDSA_P256");
            objecc.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_PUBKEY_ALG_OID_GROUP_ID, ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY, AlgorithmFlags.AlgorithmFlagsNone, "ECDSA_P256");

            //  Initialize the object ID class for the hashing algorithm (SHA384)
            objhash.InitializeFromAlgorithmName(ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID, ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY, AlgorithmFlags.AlgorithmFlagsNone, "SHA384");

            //  Provide provider name and the object id to the private key object
            pri.ProviderName = "Microsoft Software Key Storage Provider";
            pri.Algorithm    = objecc;

            //  Create the actual key pair
            pri.Create();

            //  Encode the name in using the Distinguished Name object
            dn.Encode("CN=YourName", X500NameFlags.XCN_CERT_NAME_STR_NONE);

            //  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
            p10.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextUser, pri, "");

            //  The newly created certificate request object will contain some default extensions.
            //  Suppress these defaults by setting the SuppressDefaults flag
            p10.SuppressDefaults = true;

            p10.HashAlgorithm = objhash;

            //  Assing the subject name by using the Distinguished Name object initialized above
            p10.Subject = dn;

            //  Encode the certificate request
            p10.Encode();

            //  Get the certificate request in form of a base 64 encoded string
            base64p10 = p10.get_RawData(EncodingType.XCN_CRYPT_STRING_BASE64);

            //  print the certificate request on the console
            Console.Write(base64p10);
            Console.ReadKey();

            return;
        }
Example #3
0
        public string GenerateRequest(EnrollRequestDetails pDetails)
        {
            var objPkcs10 =
                Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509CertificateRequestPkcs10")) as
                CX509CertificateRequestPkcs10;
            var objPrivateKey =
                Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509PrivateKey")) as CX509PrivateKey;
            var objCSP    = new CCspInformationClass();
            var objCSPs   = new CCspInformationsClass();
            var objDN     = new CX500DistinguishedNameClass();
            var objEnroll =
                Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509Enrollment")) as CX509Enrollment;
            var objObjectIds         = new CObjectIdsClass();
            var objObjectId          = new CObjectIdClass();
            var objExtensionKeyUsage =
                Activator.CreateInstance(
                    Type.GetTypeFromProgID("X509Enrollment.CX509ExtensionKeyUsage")) as CX509ExtensionKeyUsage;

            var objX509ExtensionEnhancedKeyUsage =
                Activator.CreateInstance(
                    Type.GetTypeFromProgID("X509Enrollment.CX509ExtensionEnhancedKeyUsage")) as
                CX509ExtensionEnhancedKeyUsage;


            try
            {
                //  Initialize the csp object using the desired Cryptograhic Service Provider (CSP)
                objCSP.InitializeFromName("Microsoft Enhanced Cryptographic Provider v1.0");

                //  Add this CSP object to the CSP collection object
                objCSPs.Add(
                    objCSP
                    );

                //  Provide key container name, key length and key spec to the private key object
                //objPrivateKey.ContainerName = "AlejaCMa";
                objPrivateKey.Length         = 4096;
                objPrivateKey.KeySpec        = X509KeySpec.XCN_AT_SIGNATURE;
                objPrivateKey.ExportPolicy   = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG;
                objPrivateKey.KeyUsage       = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_ALL_USAGES;
                objPrivateKey.MachineContext = false;

                //  Provide the CSP collection object (in this case containing only 1 CSP object)
                //  to the private key object
                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
                objPkcs10.InitializeFromPrivateKey(
                    X509CertificateEnrollmentContext.ContextUser,
                    objPrivateKey,
                    ""
                    );

                // Key Usage Extension
                objExtensionKeyUsage.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
                    );
                objPkcs10.X509Extensions.Add((CX509Extension)objExtensionKeyUsage);

                // Enhanced Key Usage Extension
                objObjectId.InitializeFromValue("1.3.6.1.5.5.7.3.2"); // OID for Client Authentication usage
                objObjectIds.Add(objObjectId);
                objX509ExtensionEnhancedKeyUsage.InitializeEncode(objObjectIds);
                objPkcs10.X509Extensions.Add((CX509Extension)objX509ExtensionEnhancedKeyUsage);

                //  Encode the name in using the Distinguished Name object
                objDN.Encode(
                    string.Format("C={0}, ST={1}, L={2}, O={3}, CN={4}, email={5},OU={6}",
                                  pDetails.Country,
                                  pDetails.County,
                                  pDetails.City,
                                  pDetails.CompanyName,
                                  pDetails.CommonName,
                                  pDetails.EmailAddress,
                                  pDetails.Department),
                    X500NameFlags.XCN_CERT_X500_NAME_STR
                    );

                //  Assing the subject name by using the Distinguished Name object initialized above
                objPkcs10.Subject = objDN;

                // Create enrollment request
                objEnroll.InitializeFromRequest(objPkcs10);
                var strRequest = objEnroll.CreateRequest(
                    EncodingType.XCN_CRYPT_STRING_BASE64
                    );
                var sb = new StringBuilder("-----BEGIN NEW CERTIFICATE REQUEST-----");
                sb.AppendLine();
                sb.Append(strRequest);
                sb.AppendLine("-----END NEW CERTIFICATE REQUEST-----");
                return(sb.ToString());
            }
            catch (Exception ex)
            {
                EventLogHelper.LogEvent(ex.Message + "\n\r" + ex.StackTrace);
                return(null);
            }
        }
		public void GenerateCsr(SSLCertificate cert)
		{
			//  Create all the objects that will be required
			CX509CertificateRequestPkcs10 pkcs10 = new CX509CertificateRequestPkcs10Class();
			CX509PrivateKey privateKey = new CX509PrivateKeyClass();
			CCspInformation csp = new CCspInformationClass();
			CCspInformations csPs = new CCspInformationsClass();
			CX500DistinguishedName dn = new CX500DistinguishedNameClass();
			CX509Enrollment enroll = new CX509EnrollmentClass();
			CObjectIds objectIds = new CObjectIdsClass();
			CObjectId clientObjectId = new CObjectIdClass();
			CObjectId serverObjectId = new CObjectIdClass();
			CX509ExtensionKeyUsage extensionKeyUsage = new CX509ExtensionKeyUsageClass();
			CX509ExtensionEnhancedKeyUsage x509ExtensionEnhancedKeyUsage = new CX509ExtensionEnhancedKeyUsageClass();

			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);
			}
		}
Example #5
0
        public void GenerateCsr(SSLCertificate cert)
        {
            //  Create all the objects that will be required
            CX509CertificateRequestPkcs10 pkcs10                         = new CX509CertificateRequestPkcs10Class();
            CX509PrivateKey        privateKey                            = new CX509PrivateKeyClass();
            CCspInformation        csp                                   = new CCspInformationClass();
            CCspInformations       csPs                                  = new CCspInformationsClass();
            CX500DistinguishedName dn                                    = new CX500DistinguishedNameClass();
            CX509Enrollment        enroll                                = new CX509EnrollmentClass();
            CObjectIds             objectIds                             = new CObjectIdsClass();
            CObjectId clientObjectId                                     = new CObjectIdClass();
            CObjectId serverObjectId                                     = new CObjectIdClass();
            CX509ExtensionKeyUsage         extensionKeyUsage             = new CX509ExtensionKeyUsageClass();
            CX509ExtensionEnhancedKeyUsage x509ExtensionEnhancedKeyUsage = new CX509ExtensionEnhancedKeyUsageClass();

            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);
            }
        }