コード例 #1
0
        private CCspInformations GetCspInformation(WindowsApi api)
        {
            CCspInformations cspList = new CCspInformations();
            CCspInformation  csp     = new CCspInformation();

            csp.InitializeFromName(GetWindowsApiProviderName(api));
            cspList.Add(csp);
            return(cspList);
        }
コード例 #2
0
        /// <summary>
        /// Certificate constructor to intialize objects and values required to create a certificate
        /// </summary>
        public Certificate()
        {
            try
            {
                // Create objects required
                objCertRequest = new CX509CertificateRequestCertificate();
                objCSP = new CCspInformation();
                objCSPs = new CCspInformations();
                objDN = new CX500DistinguishedName();
                objEnroll = new CX509Enrollment();
                objObjectId = new CObjectId();
                objPrivateKey = (IX509PrivateKey)Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509PrivateKey"));

                // Friendly name
                this.FriendlyName = "";

                // Set default values. Refer to https://msdn.microsoft.com/en-us/library/windows/desktop/aa374846(v=vs.85).aspx
                this.CryptographicProviderName = "Microsoft Enhanced Cryptographic Provider v1.0";
                this.KeySize = 2048;

                // Use key for encryption
                this.KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE;

                // The key can be used for decryption
                this.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_DECRYPT_FLAG;

                // Create for user and not machine
                this.MachineContext = false;

                // Default to expire in 1 year
                this.ExpirationLengthInDays = 365;

                // Let th private key be exported in plain text
                this.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG;

                // This is intended for a computer
                this.EnrollmentContextMachine = X509CertificateEnrollmentContext.ContextUser;

                // Use a hasing algorithm
                this.ObjectIdGroupId = ObjectIdGroupId. XCN_CRYPT_HASH_ALG_OID_GROUP_ID;
                this.ObjectIdPublicKeyFlags = ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY;
                this.AlgorithmFlags = AlgorithmFlags.AlgorithmFlagsNone;

                // Use SHA-2 with 512 bits
                this.AlgorithmName = "SHA512";
                this.EncodingType = EncodingType.XCN_CRYPT_STRING_BASE64;

                // Allow untrusted certificate to be installed
                this.InstallResponseRestrictionFlags = InstallResponseRestrictionFlags.AllowUntrustedCertificate;

                // No password set
                this.Password = null;

                // Enable key to be exported, keep the machine set, and persist the key set
                // https://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509keystorageflags(v=vs.110).aspx
                this.ExportableFlags = X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
コード例 #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);
            }
        }
コード例 #4
0
ファイル: CertificateHelper.cs プロジェクト: yvanam/SyncPro
        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));
        }
コード例 #5
0
ファイル: SSLModuleService.cs プロジェクト: pasamsin/SolidCP
        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);
            }
        }
コード例 #6
0
        /// <summary>
        /// Certificate constructor to intialize objects and values required to create a certificate
        /// </summary>
        public Certificate()
        {
            try
            {
                // Create objects required
                objCertRequest = new CX509CertificateRequestCertificate();
                objCSP         = new CCspInformation();
                objCSPs        = new CCspInformations();
                objDN          = new CX500DistinguishedName();
                objEnroll      = new CX509Enrollment();
                objObjectId    = new CObjectId();
                objPrivateKey  = (CX509PrivateKey)Activator.CreateInstance(Type.GetTypeFromProgID("X509Enrollment.CX509PrivateKey"));

                // Friendly name
                this.FriendlyName = "";

                // Set default values. Refer to https://msdn.microsoft.com/en-us/library/windows/desktop/aa374846(v=vs.85).aspx
                this.CryptographicProviderName = "Microsoft Enhanced Cryptographic Provider v1.0";
                this.KeySize = 2048;

                // Use key for encryption
                this.KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE;

                // The key can be used for decryption
                this.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_DECRYPT_FLAG;

                // Create for user and not machine
                this.MachineContext = false;

                // Default to expire in 1 year
                this.ExpirationLengthInDays = 365;

                // Let th private key be exported in plain text
                this.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG;

                // This is intended for a computer
                this.EnrollmentContextMachine = X509CertificateEnrollmentContext.ContextUser;

                // Use a hasing algorithm
                this.ObjectIdGroupId        = ObjectIdGroupId.XCN_CRYPT_HASH_ALG_OID_GROUP_ID;
                this.ObjectIdPublicKeyFlags = ObjectIdPublicKeyFlags.XCN_CRYPT_OID_INFO_PUBKEY_ANY;
                this.AlgorithmFlags         = AlgorithmFlags.AlgorithmFlagsNone;

                // Use SHA-2 with 512 bits
                this.AlgorithmName = "SHA512";
                this.EncodingType  = EncodingType.XCN_CRYPT_STRING_BASE64;

                // Allow untrusted certificate to be installed
                this.InstallResponseRestrictionFlags = InstallResponseRestrictionFlags.AllowUntrustedCertificate;

                // No password set
                this.Password = null;

                // Enable key to be exported, keep the machine set, and persist the key set
                // https://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509keystorageflags(v=vs.110).aspx
                this.ExportableFlags = X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
コード例 #7
0
            /// <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);
            }
コード例 #8
0
        public string CreateRequest()
        {
            // Create all the objects that will be required
            var    objPkcs10         = new CX509CertificateRequestPkcs10();
            var    objPrivKey        = new CX509PrivateKey();
            var    objCSP            = new CCspInformation();
            var    objCSPs           = new CCspInformations();
            var    objDN             = new CX500DistinguishedName();
            var    objEnroll         = new CX509Enrollment();
            var    objObjIds         = new CObjectIds();
            var    objObjId          = new CObjectId();
            var    objExtKeyUsage    = new CX509ExtensionKeyUsage();
            var    objExtEnhKeyUsage = new CX509ExtensionEnhancedKeyUsage();
            string strRequest;

            //objCSP.InitializeFromName(provName);
            //objCSPs.Add(objCSP);

            //objPrivKey.Length = 2048;
            //objPrivKey.KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE;
            //objPrivKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_ALL_USAGES;
            //objPrivKey.MachineContext = true;

            //objPrivKey.CspInformations = objCSPs;
            //objPrivKey.Create();

            var strTemplateName = "1.3.6.1.4.1.311.21.8.12017375.10856495.934812.8687423.15807460.10.5731641.6795722"; // RDP All Names

            objPkcs10.InitializeFromTemplateName(X509CertificateEnrollmentContext.ContextMachine, strTemplateName);

            // Encode the name in using the DN object
            objDN.Encode("CN=" + Environment.GetEnvironmentVariable("COMPUTERNAME"),
                         X500NameFlags.XCN_CERT_NAME_STR_NONE);

            // Adding the subject name by using the DN object initialized above
            objPkcs10.Subject = objDN;

            var dnsDom            = Environment.GetEnvironmentVariable("USERDNSDOMAIN").ToLower();
            var altName           = new CAlternativeName();
            var objAlternateNames = new CAlternativeNames();
            var objExtAltNames    = new CX509ExtensionAlternativeNames();

            altName.InitializeFromString(AlternativeNameType.XCN_CERT_ALT_NAME_DNS_NAME,
                                         Environment.GetEnvironmentVariable("COMPUTERNAME") + "." + dnsDom);
            var altName2 = new CAlternativeName();

            altName2.InitializeFromString(AlternativeNameType.XCN_CERT_ALT_NAME_DNS_NAME,
                                          Environment.GetEnvironmentVariable("COMPUTERNAME"));


            objAlternateNames.Add(altName2);
            objAlternateNames.Add(altName);
            objExtAltNames.InitializeEncode(objAlternateNames);
            objPkcs10.X509Extensions.Add((CX509Extension)objExtAltNames);

            // Create the enrollment request
            objEnroll.InitializeFromRequest(objPkcs10);
            strRequest = objEnroll.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64);

            return(strRequest);
        }
コード例 #9
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);
            }
        }
コード例 #10
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);
			}
		}