Esempio n. 1
3
        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;
        }
Esempio n. 2
1
        /// <summary>
        /// Submit a certificate signing request to a certificate authority, such as a server running Active Directory Certificate Services, and return the certificate or response.
        /// </summary>
        /// <param name="csr">Certificate signing request to be submitted.</param>
        /// <param name="friendlyName">The friendly name of the certificate.</param>
        /// <param name="caServer">The certificate authority server instance.</param>
        /// <param name="csrResponse">Response from the certificate signing request, represented as a CsrResponse enum.</param>
        /// <param name="dispositionMessage">Message returned when a certificate signing fails.</param>
        public X509Certificate2 SubmitCertificateSigningRequest(CX509CertificateRequestCertificate csr, string friendlyName, string caServer, out CsrResponse csrResponse, out string dispositionMessage)
        {
            // Convert the certificate signing request to base-64..
            CX509Enrollment enrollment = new CX509Enrollment();
            enrollment.InitializeFromRequest(csr);
            enrollment.CertificateFriendlyName = friendlyName;
            string csrText = enrollment.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64);

            // Submit the request to the certificate authority.
            CCertRequest certRequest = new CCertRequest();
            int csrResponseCode = certRequest.Submit(CR_IN_BASE64 | CR_IN_FORMATANY, csrText, string.Empty, caServer);

            // React to our response response from the certificate authority.
            switch (csrResponseCode)
            {
                case 3:     // Issued.
                    csrResponse = CsrResponse.CR_DISP_ISSUED;
                    dispositionMessage = "";
                    return new X509Certificate2(Encoding.UTF8.GetBytes(certRequest.GetCertificate(CR_OUT_BASE64 | CR_OUT_CHAIN)));
                case 5:     // Pending.
                    csrResponse = CsrResponse.CR_DISP_UNDER_SUBMISSION;
                    dispositionMessage = "";
                    return null;
                default:    // Failure.
                    csrResponse = CsrResponse.CR_DISP_FAILED;
                    dispositionMessage = certRequest.GetDispositionMessage();
                    return null;
            }
        }
        private string BuildEncodedCsr(CX509CertificateRequestPkcs10 pkcs10)
        {
            CX509Enrollment enrollment = new CX509Enrollment();

            enrollment.InitializeFromRequest(pkcs10);
            return(enrollment.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64));
        }
Esempio n. 4
0
        // create a certificate for testing
        // https://stackoverflow.com/q/18339706
        static public X509Certificate2 CreateSelfSignedCertificate(string subjectName, TimeSpan expirationLength)
        {
            // create DN for subject and issuer
            var dn = new CX500DistinguishedName();

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

            CX509PrivateKey privateKey = new CX509PrivateKey
            {
                ProviderName   = "Microsoft Strong Cryptographic Provider",
                Length         = 2048,
                KeySpec        = X509KeySpec.XCN_AT_KEYEXCHANGE,
                KeyUsage       = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_DECRYPT_FLAG | X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_KEY_AGREEMENT_FLAG,
                MachineContext = true,
                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");

            // 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.Date;
            // this cert expires immediately. Change to whatever makes sense for you
            cert.NotAfter      = cert.NotBefore + expirationLength;
            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)
                       // mark private key to go into the Machine store instead of the current users store
                       X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet
                       ));
        }
Esempio n. 5
0
        /// <summary>
        /// Submit a certificate signing request to a certificate authority, such as a server running Active Directory Certificate Services, and return the certificate or response.
        /// </summary>
        /// <param name="csr">Certificate signing request to be submitted.</param>
        /// <param name="friendlyName">The friendly name of the certificate.</param>
        /// <param name="caServer">The certificate authority server instance.</param>
        /// <param name="csrResponse">Response from the certificate signing request, represented as a CsrResponse enum.</param>
        /// <param name="dispositionMessage">Message returned when a certificate signing fails.</param>
        public X509Certificate2 SubmitCertificateSigningRequest(CX509CertificateRequestCertificate csr, string friendlyName, string caServer, out CsrResponse csrResponse, out string dispositionMessage)
        {
            // Convert the certificate signing request to base-64..
            CX509Enrollment enrollment = new CX509Enrollment();

            enrollment.InitializeFromRequest(csr);
            enrollment.CertificateFriendlyName = friendlyName;
            string csrText = enrollment.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64);

            // Submit the request to the certificate authority.
            CCertRequest certRequest     = new CCertRequest();
            int          csrResponseCode = certRequest.Submit(CR_IN_BASE64 | CR_IN_FORMATANY, csrText, string.Empty, caServer);

            // React to our response response from the certificate authority.
            switch (csrResponseCode)
            {
            case 3:         // Issued.
                csrResponse        = CsrResponse.CR_DISP_ISSUED;
                dispositionMessage = "";
                return(new X509Certificate2(Encoding.UTF8.GetBytes(certRequest.GetCertificate(CR_OUT_BASE64 | CR_OUT_CHAIN))));

            case 5:         // Pending.
                csrResponse        = CsrResponse.CR_DISP_UNDER_SUBMISSION;
                dispositionMessage = "";
                return(null);

            default:        // Failure.
                csrResponse        = CsrResponse.CR_DISP_FAILED;
                dispositionMessage = certRequest.GetDispositionMessage();
                return(null);
            }
        }
        /// <summary>
        /// Creates a self signed certificate given the parameters.
        /// </summary>
        /// <param name="subject"></param>
        /// <param name="cipher"></param>
        /// <param name="keysize"></param>
        /// <param name="api"></param>
        /// <returns></returns>
        public X509Certificate2 CreateSelfSignedCertificate(CertificateSubject subject, CipherAlgorithm cipher, int keysize, WindowsApi api)
        {
            CX509PrivateKey privateKey = CreatePrivateKey(cipher, keysize);
            CX509CertificateRequestCertificate pkcs10 = NewCertificateRequestCrc(subject, privateKey);

            pkcs10.Issuer    = pkcs10.Subject;
            pkcs10.NotBefore = DateTime.Now.AddDays(-1);
            pkcs10.NotAfter  = DateTime.Now.AddYears(20);
            var sigoid = new CObjectId();
            var alg    = new Oid("SHA256");

            sigoid.InitializeFromValue(alg.Value);
            pkcs10.SignatureInformation.HashAlgorithm = sigoid;
            pkcs10.Encode();

            CX509Enrollment enrollment = new CX509Enrollment();

            enrollment.InitializeFromRequest(pkcs10);

            string csr = enrollment.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64);
            InstallResponseRestrictionFlags restrictionFlags = InstallResponseRestrictionFlags.AllowUntrustedCertificate;

            enrollment.InstallResponse(restrictionFlags, csr, EncodingType.XCN_CRYPT_STRING_BASE64, string.Empty);

            string pwd = secret.NewSecret(16);
            string pfx = enrollment.CreatePFX(pwd, PFXExportOptions.PFXExportChainWithRoot, EncodingType.XCN_CRYPT_STRING_BASE64);

            return(new X509Certificate2(Convert.FromBase64String(pfx), pwd));
        }
Esempio n. 7
0
        /// <summary>
        /// Generate a self-signed certificate and add it to the Windows certificate store.
        /// </summary>
        /// <param name="subjectName">The subject name of the certificate.</param>
        /// <param name="friendlyName">The friendly name of the certificate.</param>
        /// <param name="location">Location of the certificate; either the Current User or Local Machine.</param>
        /// <param name="addAsTrustedRoot">Whether to add the generated certificate as a trusted root.</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 X509Certificate2 CreateSelfSignedCertificate(string subjectName, string friendlyName, StoreLocation location, bool addAsTrustedRoot, int keyLength, int durationYears, List <string> oids)
        {
            // Create the self-signing request.
            CX509CertificateRequestCertificate cert = CreateCertificateSigningRequest(subjectName, keyLength, durationYears, oids);

            // Enroll based on the certificate signing request.
            CX509Enrollment enrollment = new CX509Enrollment();

            enrollment.InitializeFromRequest(cert);
            enrollment.CertificateFriendlyName = friendlyName;
            string csrText = enrollment.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64);

            // Install the certificate chain.  Note that no password is specified.
            enrollment.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedCertificate, csrText, EncodingType.XCN_CRYPT_STRING_BASE64, "");

            // Base-64 encode the PKCS#12 certificate in order to re-import it.
            string pfx = enrollment.CreatePFX("", PFXExportOptions.PFXExportChainWithRoot);

            // Instantiate the PKCS#12 certificate.
            X509Certificate2 certificate = new X509Certificate2(System.Convert.FromBase64String(pfx), "", X509KeyStorageFlags.Exportable);

            // If specified, also install the certificate to the trusted root store.
            if (addAsTrustedRoot)
            {
                X509Store rootStore = new X509Store(StoreName.Root, location);
                rootStore.Open(OpenFlags.ReadWrite);
                rootStore.Add(certificate);
                rootStore.Close();
            }

            return(certificate);
        }
Esempio n. 8
0
        static void Main()
        {
            CX509Enrollment enroll = new CX509Enrollment();
            CX509PrivateKey pri    = new CX509PrivateKey();
            CX509CertificateRequestPkcs10 request = new CX509CertificateRequestPkcs10();
            CX500DistinguishedName        dn      = new CX500DistinguishedName();

            pri.ProviderName = "eToken Base Cryptographic Provider";
            pri.Length       = 2048;
            pri.KeySpec      = X509KeySpec.XCN_AT_KEYEXCHANGE;

            //pri.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_DECRYPT_FLAG;

            pri.ProviderType = X509ProviderType.XCN_PROV_RSA_FULL;
            pri.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_NONE;

            request.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextUser, pri, "");
            dn.Encode("CN=KimiNoNaWa", X500NameFlags.XCN_CERT_NAME_STR_DISABLE_UTF8_DIR_STR_FLAG);
            request.Subject = dn;

            enroll.InitializeFromRequest(request);
            string pkcs10 = enroll.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64);

            Console.WriteLine(pkcs10);

            //Do Enrollment

            //Install certificate
            //enroll.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedRoot, pkcs10, EncodingType.XCN_CRYPT_STRING_BASE64REQUESTHEADER, "");
        }
        private string CreateCertificate(string publisherName)
        {
            var cert = CreateCertificateRequest(publisherName);

            AddKeyUsage(cert);
            AddExtendedKeyUsage(cert);
            AddBasicConstraints(cert);

            // Specify the 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, "SHA256");

            cert.HashAlgorithm = hashobj;
            cert.Encode();

            // Do the final enrollment process
            var enrollment = new CX509Enrollment();

            enrollment.InitializeFromRequest(cert); // load the certificate
            enrollment.CertificateFriendlyName = cert.Subject.Name;

            var request = enrollment.CreateRequest();

            enrollment.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedCertificate, request, EncodingType.XCN_CRYPT_STRING_BASE64, "");

            var base64Encoded = enrollment.CreatePFX("", PFXExportOptions.PFXExportChainWithRoot);

            return(base64Encoded);
        }
Esempio n. 10
0
        public static X509Certificate2 CreateSelfSignedCertificate(string subjectName)
        {
            //To make a certificate was used system library from CERTENROLLLib
            //This lib provides methods for creation certificates in windows envinronment


            //Defines the subject and issuer of the cert
            CX500DistinguishedName dn = new CX500DistinguishedName();

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

            //Create a new private key for the certificate
            //Was decided not to make them variably in this progr
            CX509PrivateKey privateKey = new CX509PrivateKey();

            privateKey.ProviderName   = "Microsoft Base Cryptographic Provider v1.0"; //issuer for a selfsigned certificate
            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 trong 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");

            // 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;
            cert.NotAfter      = new DateTime(2018, 12, 31); // I don't think that anybody cares about using this cert longer than this period
            cert.HashAlgorithm = hashobj;                    // Specify the hashing algorithm
            cert.Encode();                                   // Encode the certificate

            // Do the final stuff
            //Enroll is
            var enroll = new CX509Enrollment();

            enroll.InitializeFromRequest(cert);  // load the certificate
            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("",                               // password isn't possible
                                                 PFXExportOptions.PFXExportChainWithRoot);

            // instantiate the target class with the PKCS#12 data (and the empty password)
            return(new X509Certificate2(Convert.FromBase64String(base64encoded), "",
                                        // mark the private key as exportable, coz we want to put it into registry
                                        X509KeyStorageFlags.Exportable));
        }
Esempio n. 11
0
        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));
        }
Esempio n. 13
0
        internal static Pkcs10CertificationRequest createKeyPair()
        {
            var objCSPs = new CCspInformations();

            objCSPs.AddAvailableCsps();


            var objPrivateKey = new CX509PrivateKey();

            objPrivateKey.Length          = 1024;
            objPrivateKey.KeySpec         = X509KeySpec.XCN_AT_SIGNATURE;
            objPrivateKey.KeyUsage        = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_ALL_USAGES;
            objPrivateKey.MachineContext  = false;
            objPrivateKey.ExportPolicy    = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG;
            objPrivateKey.CspInformations = objCSPs;
            objPrivateKey.Create();

            var objPkcs10 = new CX509CertificateRequestPkcs10();

            objPkcs10.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextUser,
                                               objPrivateKey,
                                               string.Empty);

            //var objExtensionKeyUsage = new CX509ExtensionKeyUsage();
            //objExtensionKeyUsage.InitializeEncode(
            //    CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_KEY_CERT_SIGN_KEY_USAGE |
            //    CERTENROLLLib.X509KeyUsageFlags.XCN_CERT_CRL_SIGN_KEY_USAGE);

            //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.2");
            //objObjectIds.Add(objObjectId);
            //objX509ExtensionEnhancedKeyUsage.InitializeEncode(objObjectIds);
            //objPkcs10.X509Extensions.Add((CX509Extension)objX509ExtensionEnhancedKeyUsage);

            var objDN       = new CX500DistinguishedName();
            var subjectName = "CN = shaunxu.me, OU = ADCS, O = Blog, L = Beijng, S = Beijing, C = CN";

            objDN.Encode(subjectName, X500NameFlags.XCN_CERT_NAME_STR_NONE);
            objPkcs10.Subject = objDN;

            var objEnroll = new CX509Enrollment();

            objEnroll.InitializeFromRequest(objPkcs10);
            var strRequest = objEnroll.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64);

            Pkcs10CertificationRequest p10 = new Pkcs10CertificationRequest(Convert.FromBase64String(strRequest));

            return(p10);
        }
        private X509Certificate2 CreateNewCertificate(CX509CertificateRequestCertificate cert)
        {
            var enr = new CX509Enrollment
            {
                CertificateFriendlyName = FriendlyName
            };

            enr.InitializeFromRequest(cert);
            string endCert = enr.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64);

            enr.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedCertificate, endCert, EncodingType.XCN_CRYPT_STRING_BASE64, string.Empty);

            byte[] certBytes = Convert.FromBase64String(endCert);
            return(new X509Certificate2(certBytes));
        }
Esempio n. 15
0
        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);
        }
        /// <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;
            }
        }
Esempio n. 17
0
        //rennew certficiate that expired
        public int RenewCert(string Cert, int reqid)
        {
            int    iDisposition;
            string CertifcateStr;
            string status;
            string HostName;
            CX509CertificateRequestPkcs10 objPkcs10 = new CX509CertificateRequestPkcs10();
            CX509Enrollment        objEnroll        = new CX509Enrollment();
            CCertConfig            objCertConfig    = new CCertConfig();
            CX500DistinguishedName objDN            = new CX500DistinguishedName();
            CCertAdmin             objCertAdmin     = new CCertAdmin();
            string strCAConfig;
            var    inheritOptions = X509RequestInheritOptions.InheritPrivateKey | X509RequestInheritOptions.InheritSubjectFlag | X509RequestInheritOptions.InheritExtensionsFlag | X509RequestInheritOptions.InheritSubjectAltNameFlag;

            try
            {
                strCAConfig = objCertConfig.GetConfig(CC_DEFAULTCONFIG);                                                                                             //connect to the  ca
                InstallCert(Cert);
                objPkcs10.InitializeFromCertificate(X509CertificateEnrollmentContext.ContextUser, Cert, EncodingType.XCN_CRYPT_STRING_BASE64HEADER, inheritOptions); //create new cert request from exists expired cert
                objDN    = objPkcs10.Subject;                                                                                                                        //getting old cert subject (hostname)
                HostName = objDN.Name.ToString().Substring(3);
                objEnroll.InitializeFromRequest(objPkcs10);                                                                                                          //create enroll rquest
                CertifcateStr = objEnroll.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64);                                                                       //crearte  new cert request
                Database db   = new Database();
                var      cert = db.ReturnCertificateInformation(HostName);
                db.DeleteCertificateRecordFromDb(reqid);
                // revokeCert(cert.serialnumber);
                iDisposition = SubmitRequest(CertifcateStr, HostName);   //submit cert to the ca
                objCertAdmin.ResubmitRequest(strCAConfig, iDisposition); //issue the Certificate

                if (iDisposition > 0)                                    //if cert was created delete the old cert from the table
                {
                    DeleteCertificateFromStore(objDN.Name.ToString());
                    return(iDisposition);
                }
                return(0);
            }

            catch (Exception ex)
            {
                status = ex.Message;
                Database db = new Database();
                db.InsertToErrorMessageTable("", reqid, ex.Message, "RenewCert");//insert Error Message into The Error Table Log In The DataBase
                return(1);
            }
        }
Esempio n. 18
0
        public virtual string CreateRequest()
        {
            Trace.TraceInformation(Resources.CertificateCreateRequest);

            if (Request == null)
            {
                Trace.TraceError(Resources.CertificateCreateRequestNull);
                throw new InvalidOperationException(Resources.CertificateCreateRequestNull);
            }

            var enrollment =
                new CX509Enrollment();

            enrollment.InitializeFromRequest(Request);

            var request =
                enrollment.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64REQUESTHEADER);

            return(request);
        }
Esempio n. 19
0
        public string CreateTemplateRequest(string cn, string ou, string o, string l, string s, string c,
                                            int keyLength,
                                            string templateName)
        {
            var csp = new CCspInformations();

            csp.AddAvailableCsps();
            var privateKey = new 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 = new CX509CertificateRequestPkcs10();

            pkcs10.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextUser,
                                            privateKey,
                                            templateName);

            var san = GetSAN(cn);

            pkcs10.X509Extensions.Add((CX509Extension)san);

            var distinguishedName = new CX500DistinguishedName();

            var subjectName = $"{cn},OU = {ou},O = {o} ,L = {l},S = {s},C = {c}";

            distinguishedName.Encode(subjectName);
            pkcs10.Subject = distinguishedName;

            var enroll = new CX509Enrollment();

            enroll.InitializeFromRequest(pkcs10);
            var strRequest = enroll.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64HEADER);

            return(strRequest);
        }
        /// <summary>
        /// The create active directory certificate request.
        /// </summary>
        /// <param name="templateName">
        /// The template name.
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        public string CreateActiveDirectoryCertificateRequest(string templateName)
        {
            //// https://blogs.msdn.microsoft.com/alejacma/2008/09/05/how-to-create-a-certificate-request-with-certenroll-and-net-c/
            //// http://geekswithblogs.net/shaunxu/archive/2012/01/13/working-with-active-directory-certificate-service-via-c.aspx

            this.LastError.Clear();
            try
            {
                var cspInformations = new CCspInformations();
                cspInformations.AddAvailableCsps();

                var privateKey = new CX509PrivateKey // Создали приватный ключ
                {
                    Length          = 2048,
                    KeySpec         = X509KeySpec.XCN_AT_SIGNATURE,
                    KeyUsage        = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_ALL_USAGES,
                    MachineContext  = false,
                    ExportPolicy    = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG,
                    CspInformations = cspInformations
                };

                privateKey.Create();

                var objPkcs10 = new CX509CertificateRequestPkcs10();
                objPkcs10.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextUser, privateKey, templateName);
                var objEnroll = new CX509Enrollment();
                objEnroll.InitializeFromRequest(objPkcs10);
                var strRequest = objEnroll.CreateRequest(); // Значение по уолчанию: EncodingType.XCN_CRYPT_STRING_BASE64
                return(strRequest);
            }
            catch (Exception ex)
            {
                this.LastError.Add(ex.Message);
                return(string.Empty);
            }
        }
Esempio n. 21
0
        /// <summary>
        /// Generates a certificate signing request for use with Xbox Live.
        /// </summary>
        public string GenerateCertRequest()
        {
            this.EnsureAdmin();

            CX509CertificateRequestCertificate certRequest = new CX509CertificateRequestCertificate();

            certRequest.Initialize(X509CertificateEnrollmentContext.ContextMachine);
            certRequest.PrivateKey.Length       = 2048;
            certRequest.PrivateKey.ProviderName = "Microsoft Enhanced RSA and AES Cryptographic Provider";
            certRequest.PrivateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_PLAINTEXT_EXPORT_FLAG;

            CX500DistinguishedName subject = new CX500DistinguishedName();

            subject.Encode("CN=NOT USED");
            certRequest.Subject = subject;

            CX509Enrollment enroll = new CX509Enrollment();

            enroll.InitializeFromRequest(certRequest);
            enroll.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64HEADER);

            this.privateKey = certRequest.PrivateKey.Export("PRIVATEBLOB", EncodingType.XCN_CRYPT_STRING_BASE64).ToSecureString();
            return(certRequest.PrivateKey.Export("PUBLICBLOB", EncodingType.XCN_CRYPT_STRING_BASE64 | EncodingType.XCN_CRYPT_STRING_NOCRLF));
        }
        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);
        }
Esempio n. 23
0
    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]);
        }
    }
Esempio n. 24
0
		private static string CreateCertContent(string cn, TimeSpan expirationLength, string pwd)
		{
			var base64encoded = string.Empty;
			var dn = new CX500DistinguishedName();
			dn.Encode("CN=" + cn, X500NameFlags.XCN_CERT_NAME_STR_NONE);

			var privateKey = new CX509PrivateKey();
			privateKey.ProviderName = "Microsoft Strong Cryptographic Provider";
			privateKey.Length = 2048;
			privateKey.KeySpec = X509KeySpec.XCN_AT_KEYEXCHANGE;
			privateKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_DECRYPT_FLAG |
			                      X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_KEY_AGREEMENT_FLAG;
			privateKey.MachineContext = true;
			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, "SHA256");

			// 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.Date;
			// this cert expires immediately. Change to whatever makes sense for you
			cert.NotAfter = cert.NotBefore + expirationLength;
			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 = cn; // Optional: add a friendly name
			var 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, pwd); // no password
			// output a base64 encoded PKCS#12 so we can import it back to the .Net security classes
			base64encoded = enroll.CreatePFX(pwd, // no password, this is for internal consumption
				PFXExportOptions.PFXExportChainWithRoot);
			return base64encoded;
		}
Esempio n. 25
0
        // 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);
        }
Esempio n. 26
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);
            }
        }
Esempio n. 27
0
        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);
        }
Esempio n. 28
0
      /*
       * http://stackoverflow.com/questions/13806299/how-to-create-a-self-signed-certificate-using-c
       * This implementation uses the CX509CertificateRequestCertificate COM object (and friends - MSDN doc) from certenroll.dll to create a self signed certificate request and sign it. 
       */
      public static X509Certificate2 CreateSelfSignedCertificateCOM(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 Enhanced RSA and AES Cryptographic Provider";
          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.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_SIGNING_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");

          // 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.Subtract(new TimeSpan(1, 0, 0, 0));
          cert.NotAfter = DateTime.Now.Add(new TimeSpan(30,0,0,0));
          //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
          );
      }
Esempio n. 29
0
        private static string CreateCertContent(string cn, TimeSpan expirationLength, string pwd)
        {
            string base64encoded = string.Empty;
            var    dn            = new CERTENROLLLib.CX500DistinguishedName();

            dn.Encode("CN=" + cn, X500NameFlags.XCN_CERT_NAME_STR_NONE);



            CX509PrivateKey privateKey = new CX509PrivateKey();

            privateKey.ProviderName = "Microsoft Strong Cryptographic Provider";
            privateKey.Length       = 2048;
            privateKey.KeySpec      = X509KeySpec.XCN_AT_KEYEXCHANGE;
            privateKey.KeyUsage     = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_DECRYPT_FLAG |
                                      X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_KEY_AGREEMENT_FLAG;
            privateKey.MachineContext = true;
            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");

            // 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.Date;



            var objExtensionAlternativeNames = new CX509ExtensionAlternativeNames();

            {
                var altNames = new CAlternativeNames();
                //var 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.AddressFamily == AddressFamily.InterNetworkV6) && !IPAddress.IsLoopback(ipAddress))
                //    {
                //        var dns = new CAlternativeName();
                //        dns.InitializeFromString(AlternativeNameType.XCN_CERT_ALT_NAME_DNS_NAME, ipAddress.ToString());
                //        altNames.Add(dns);
                //    }
                //}
                var dns1 = new CAlternativeName();
                dns1.InitializeFromString(AlternativeNameType.XCN_CERT_ALT_NAME_DNS_NAME, "localhost");
                altNames.Add(dns1);
                objExtensionAlternativeNames.InitializeEncode(altNames);
            }

            cert.X509Extensions.Add((CX509Extension)objExtensionAlternativeNames);

            // this cert expires immediately. Change to whatever makes sense for you
            cert.NotAfter      = cert.NotBefore + expirationLength;
            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 = cn; // 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, pwd); // no password
            // output a base64 encoded PKCS#12 so we can import it back to the .Net security classes
            base64encoded = enroll.CreatePFX(pwd,                                   // no password, this is for internal consumption
                                             PFXExportOptions.PFXExportChainWithRoot);
            return(base64encoded);
        }
Esempio n. 30
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));
        }
        static void Main(string[] args)
        {
            string requesterName = @"DOMAIN\otherUser";
            string caName        = @"CA1.DOMAIN.LOCAL\DOMAIN-CA1-CA";
            string template      = "User";
            // signerCertificate's private key must be accessible to this process
            var signerCertificate = FindCertificateByThumbprint("3f817d138f32a9a8df2aa6e43b8aed76eb93a932");

            // 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 Enhanced Cryptographic Provider v1.0";
            privateKey.MachineContext = false;
            privateKey.Length         = 2048;
            privateKey.KeySpec        = X509KeySpec.XCN_AT_KEYEXCHANGE;
            privateKey.ExportPolicy   = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_NONE;
            privateKey.Create();

            // PKCS 10 Request
            // we use v1 to avoid compat issues on w2k8
            IX509CertificateRequestPkcs10 req = (IX509CertificateRequestPkcs10) new CX509CertificateRequestPkcs10();

            req.InitializeFromPrivateKey(X509CertificateEnrollmentContext.ContextUser, privateKey, template);

            // PKCS 7 Wrapper
            var signer = new CSignerCertificate();

            signer.Initialize(false, X509PrivateKeyVerify.VerifyAllowUI, EncodingType.XCN_CRYPT_STRING_BASE64_ANY,
                              Convert.ToBase64String(signerCertificate.GetRawCertData()));

            var wrapper = new CX509CertificateRequestPkcs7();

            wrapper.InitializeFromInnerRequest(req);
            wrapper.RequesterName     = requesterName;
            wrapper.SignerCertificate = signer;

            // get CSR
            var enroll = new CX509Enrollment();

            enroll.InitializeFromRequest(wrapper);
            var csr = enroll.CreateRequest();
            //File.WriteAllText("csr.p7b", csr);

            // submit
            const int     CR_IN_BASE64 = 1, CR_OUT_BASE64 = 1;
            const int     CR_IN_PKCS7 = 0x300;
            ICertRequest2 liveCsr     = new CCertRequest();
            var           disposition = (RequestDisposition)liveCsr.Submit(CR_IN_BASE64 | CR_IN_PKCS7, csr, null, caName);

            if (disposition == RequestDisposition.CR_DISP_ISSUED)
            {
                string resp = liveCsr.GetCertificate(CR_OUT_BASE64);
                //File.WriteAllText("resp.cer", resp);

                // install the response
                var install = new CX509Enrollment();
                install.Initialize(X509CertificateEnrollmentContext.ContextUser);

                install.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedRoot,
                                        resp, EncodingType.XCN_CRYPT_STRING_BASE64_ANY, null);
            }
            else
            {
                Console.WriteLine("disp: " + disposition.ToString());
            }
            Console.WriteLine("done");
            Console.ReadLine();
        }
        /// <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
                       ));
        }
Esempio n. 33
0
        /// <summary>
        /// Generate a self-signed certificate and add it to the Windows certificate store.
        /// </summary>
        /// <param name="subjectName">The subject name of the certificate.</param>
        /// <param name="friendlyName">The friendly name of the certificate.</param>
        /// <param name="location">Location of the certificate; either the Current User or Local Machine.</param>
        /// <param name="addAsTrustedRoot">Whether to add the generated certificate as a trusted root.</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 X509Certificate2 CreateSelfSignedCertificate(string subjectName, string friendlyName, StoreLocation location, bool addAsTrustedRoot, int keyLength, int durationYears, List<string> oids)
        {
            // Create the self-signing request.
            CX509CertificateRequestCertificate cert = CreateCertificateSigningRequest(subjectName, keyLength, durationYears, oids);

            // Enroll based on the certificate signing request.
            CX509Enrollment enrollment = new CX509Enrollment();
            enrollment.InitializeFromRequest(cert);
            enrollment.CertificateFriendlyName = friendlyName;
            string csrText = enrollment.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64);

            // Install the certificate chain.  Note that no password is specified.
            enrollment.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedCertificate, csrText, EncodingType.XCN_CRYPT_STRING_BASE64, "");

            // Base-64 encode the PKCS#12 certificate in order to re-import it.
            string pfx = enrollment.CreatePFX("", PFXExportOptions.PFXExportChainWithRoot);

            // Instantiate the PKCS#12 certificate.
            X509Certificate2 certificate = new X509Certificate2(System.Convert.FromBase64String(pfx), "", X509KeyStorageFlags.Exportable);

            // If specified, also install the certificate to the trusted root store.
            if (addAsTrustedRoot)
            {
                X509Store rootStore = new X509Store(StoreName.Root, location);
                rootStore.Open(OpenFlags.ReadWrite);
                rootStore.Add(certificate);
                rootStore.Close();
            }

            return certificate;
        }
Esempio n. 34
0
        public string CreateTemplateRequest(string cn, string ou, string o, string l, string s, string c, int keylength, string template)
        {
            var objCSPs = new CCspInformations();
                objCSPs.AddAvailableCsps();
                var objPrivateKey = new CX509PrivateKey();
                objPrivateKey.Length = keylength;
                objPrivateKey.KeySpec = X509KeySpec.XCN_AT_SIGNATURE;
                objPrivateKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_ALL_USAGES;
                objPrivateKey.MachineContext = false;
                objPrivateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG;
                objPrivateKey.CspInformations = objCSPs;
                objPrivateKey.Create();

                var objPkcs10 = new CX509CertificateRequestPkcs10();
                objPkcs10.InitializeFromPrivateKey(
                    X509CertificateEnrollmentContext.ContextUser,
                    objPrivateKey,
                    template);

                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);
                objPkcs10.Subject = objDN;

                var objEnroll = new CX509Enrollment();
                objEnroll.InitializeFromRequest(objPkcs10);
                var strRequest = objEnroll.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64);

                return strRequest;
        }
Esempio n. 35
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);
            }
        }
        /// <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);
        }
Esempio n. 37
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);
			}
		}