예제 #1
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;
            }
        }
예제 #2
1
        private void btn_savepfx_Click(object sender, RoutedEventArgs e)
        {
            string passwd = txt_Pfxpasswd.Password;
            string caserver = txt_CAServer.Text;
            string dir = Directory.GetParent(Assembly.GetExecutingAssembly().Location).ToString();

            if (Certs.Count == 0)
            {
                MessageBox.Show("No Request(s) To Save");
                return;
            }

            foreach (Certificates c in Certs)
            {
                if (c.Status != "File Created!" && c.Status == "certificate issued")
                {

                CX509Enrollment objEnroll = new CX509EnrollmentClass();
                var objCertRequest = new CCertRequest();

                var iDisposition = objCertRequest.RetrievePending(Convert.ToInt32(c.ID), caserver);

                if (Convert.ToInt32(iDisposition) == 3)
                {
                    var cert = objCertRequest.GetCertificate(CR_OUT_BASE64 | CR_OUT_CHAIN);

                    objEnroll.Initialize(X509CertificateEnrollmentContext.ContextUser);
                    objEnroll.InstallResponse(
                        InstallResponseRestrictionFlags.AllowUntrustedRoot,
                        cert,
                        EncodingType.XCN_CRYPT_STRING_BASE64,
                        null
                    );

                    c.Status = "File Created!";

                    var fil = objEnroll.CreatePFX(passwd, PFXExportOptions.PFXExportChainWithRoot, EncodingType.XCN_CRYPT_STRING_BASE64);
                    System.IO.File.WriteAllText(dir + @"\" + c.FQDN + ".pfx", fil);
                }

            }

            }
        }
예제 #3
1
        public static bool Enroll(string username, WindowsCertificate agentCertificate, string caConfig, string template, string csr, out string errorMessage, out X509Certificate2 cert)
        {
            errorMessage = null;
            cert         = null;

            string argsUser = username;

            X509Store store = new X509Store("My", StoreLocation.CurrentUser);

            store.Open(OpenFlags.ReadOnly);

            // Create a PKCS 10 inner request.
            CX509CertificateRequestPkcs10 pkcs10Req;

            try
            {
                pkcs10Req = new CX509CertificateRequestPkcs10();
                pkcs10Req.InitializeDecode(csr, EncodingType.XCN_CRYPT_STRING_BASE64_ANY);
            }
            catch (Exception ex)
            {
                errorMessage = "Unable to create PKCS10 request, malformed CSR?" + Environment.NewLine + ex.Message;
                return(false);
            }

            // Create a CMC outer request and initialize
            CX509CertificateRequestCmc cmcReq;

            try
            {
                cmcReq = new CX509CertificateRequestCmc();
                cmcReq.InitializeFromInnerRequestTemplateName(pkcs10Req, template);
                cmcReq.RequesterName = argsUser;
            }
            catch (Exception ex)
            {
                errorMessage = "Unable to create CMC request, bad certificate template?" + Environment.NewLine + ex.Message;
                return(false);
            }

            if (agentCertificate.StoreLocation == StoreLocation.CurrentUser)
            {
                try
                {
                    CSignerCertificate signer = new CSignerCertificate();
                    signer.Initialize(false, X509PrivateKeyVerify.VerifyNone, EncodingType.XCN_CRYPT_STRING_HEXRAW, agentCertificate.Certificate.Thumbprint);
                    cmcReq.SignerCertificate = signer;
                }
                catch (COMException ex) when(ex.HResult == (int)WindowsCryptoApiErrors.CRYPT_E_NOT_FOUND)
                {
                    errorMessage = "Agent certificate was not found in the CurrentUser store";
                    return(false);
                }
                catch (COMException ex) when(ex.HResult == (int)WindowsCryptoApiErrors.NTE_NO_KEY)
                {
                    errorMessage = "Could not access the key of the agent certificate. Perhaps you do not have permissions for it?" + Environment.NewLine + Environment.NewLine + "Consult the manual for more information";
                    return(false);
                }
                catch (Exception ex)
                {
                    errorMessage = "Unable to initialize signer, bad agent certificate?" + Environment.NewLine + ex.Message;
                    return(false);
                }
            }
            else if (agentCertificate.StoreLocation == StoreLocation.LocalMachine)
            {
                try
                {
                    CSignerCertificate signer = new CSignerCertificate();
                    signer.Initialize(true, X509PrivateKeyVerify.VerifyNone, EncodingType.XCN_CRYPT_STRING_HEXRAW, agentCertificate.Certificate.Thumbprint);
                    cmcReq.SignerCertificate = signer;
                }
                catch (COMException ex) when(ex.HResult == (int)WindowsCryptoApiErrors.CRYPT_E_NOT_FOUND)
                {
                    errorMessage = "Agent certificate was not found in the LocalMachine store";
                    return(false);
                }
                catch (COMException ex) when(ex.HResult == (int)WindowsCryptoApiErrors.NTE_NO_KEY)
                {
                    errorMessage = "Could not access the key of the agent certificate. Perhaps you do not have permissions for it?" + Environment.NewLine + Environment.NewLine + "Consult the manual for more information";
                    return(false);
                }
                catch (Exception ex)
                {
                    errorMessage = "Unable to initialize signer, bad agent certificate?" + Environment.NewLine + ex.Message;
                    return(false);
                }
            }
            else
            {
                errorMessage = "Agent certificate was not found in any store";
                return(false);
            }

            // encode the request
            cmcReq.Encode();

            string strRequest = cmcReq.RawData[EncodingType.XCN_CRYPT_STRING_BASE64];

            CCertRequest objCertRequest = new CCertRequest();

            // Get CA config from UI
            string strCAConfig = caConfig;

            // Submit the request
            int iDisposition;

            try
            {
                iDisposition = objCertRequest.Submit(CR_IN_BASE64 | CR_IN_FORMATANY, strRequest, null, strCAConfig);
            }
            catch (Exception ex)
            {
                errorMessage = "Unable to submit signing request, bad CA config?" + Environment.NewLine + ex.Message;
                return(false);
            }

            // Check the submission status
            if (CR_DISP_ISSUED != iDisposition) // Not enrolled
            {
                string strDisposition = objCertRequest.GetDispositionMessage();

                errorMessage = strDisposition;
                if (CR_DISP_UNDER_SUBMISSION == iDisposition)
                {
                    return(false);
                }

                errorMessage = errorMessage + Environment.NewLine + objCertRequest.GetLastStatus();
                return(false);
            }

            // Get the certificate
            string strCert = objCertRequest.GetCertificate(CR_OUT_BASE64);

            byte[] rawCert = Convert.FromBase64String(strCert);

            cert = new X509Certificate2(rawCert);
            return(true);
        }
예제 #4
1
        public string SendRequest(string request, string caserver)
        {
            var objCertRequest = new CCertRequest();
            var iDisposition = objCertRequest.Submit(
                    (int)Encoding.CR_IN_BASE64 | (int)Format.CR_IN_FORMATANY,                                                                            //http://msdn.microsoft.com/en-us/library/windows/desktop/aa385054(v=vs.85).aspx
                    request,
                    string.Empty,
                    caserver);

            return objCertRequest.GetRequestId().ToString();
        }
        public string SendRequestToCA(string certRequest)
        {
            // Create objects
            var certConfig     = new CCertConfig();
            var objCertRequest = new CCertRequest();
            var caConfig       = certConfig.GetConfig(CC_DEFAULTCONFIG);

            // Submit the request

            var iDisposition = objCertRequest.Submit(
                CR_IN_BASE64 | CR_IN_FORMATANY,
                certRequest,
                null,
                caConfig
                );

            // Check the submission status
            if (CR_DISP_ISSUED != iDisposition)  // Not enrolled
            {
                var strDis = objCertRequest.GetDispositionMessage();
                Console.WriteLine(strDis);
            }

            // Get the certificate
            var strCert = objCertRequest.GetCertificate(CR_OUT_BASE64 | CR_OUT_CHAIN);

            return(strCert);
        }
예제 #6
0
        public string SendRequest(string createRequest, string caServer,
                                  string templateName,
                                  string additionalAttributes = "")
        {
            var attributes = string.Format("CertificateTemplate: {0}", templateName);

            if (!string.IsNullOrEmpty(additionalAttributes))
            {
                attributes += "\n" + additionalAttributes;
            }

            var certRequest   = new CCertRequest();
            var requestResult =
                (RequestDisposition)certRequest.Submit((int)EncodingType.XCN_CRYPT_STRING_BASE64HEADER,
                                                       createRequest,
                                                       attributes,
                                                       caServer);
            string cert = null;

            if (requestResult == RequestDisposition.CR_DISP_ISSUED)
            {
                cert = certRequest.GetCertificate((int)EncodingType.XCN_CRYPT_STRING_BASE64REQUESTHEADER);
            }

            return(cert);
        }
예제 #7
0
        public string RetrieveCertStatus(int id, string caServer)
        {
            int strDisposition;
            var msg = "";

            var objCertRequest = new CCertRequest();

            strDisposition = objCertRequest.RetrievePending(id, caServer);

            switch (strDisposition)
            {
            case (int)RequestDisposition.CR_DISP_INCOMPLETE:
                msg = "incomplete certificate";
                break;

            case (int)RequestDisposition.CR_DISP_DENIED:
                msg = "request denied";
                break;

            case (int)RequestDisposition.CR_DISP_ISSUED:
                msg = "certificate issued";
                break;

            case (int)RequestDisposition.CR_DISP_UNDER_SUBMISSION:
                msg = "request pending";
                break;

            case (int)RequestDisposition.CR_DISP_REVOKED:
                msg = "certificate revoked";
                break;
            }

            return(msg);
        }
예제 #8
0
        /// <summary>
        /// Retrieves the most recent 'CA Exchange' certificate. If the certificate does not exist, the method
        /// will instruct CA server to generate or enroll a new one.
        /// </summary>
        /// <exception cref="UninitializedObjectException">The object is not properly initialized.</exception>
        /// <exception cref="ServerUnavailableException">CA server is not accessible via RPC/DCOM.</exception>
        /// <exception cref="UnauthorizedAccessException">The caller do not have at least <strong>Read</strong> permissions.</exception>
        /// <exception cref="PlatformNotSupportedException">Current CA is not <strong>Enterprise CA</strong>. Only Enterprise CAs supports this feature.</exception>
        /// <returns>CA Exchange certificate.</returns>
        public X509Certificate2 GetCAExchangeCertificate()
        {
            if (String.IsNullOrEmpty(Name))
            {
                throw new UninitializedObjectException();
            }
            if (!IsEnterprise)
            {
                throw new PlatformNotSupportedException(Error.E_NONENTERPRISE);
            }
            if (!Ping())
            {
                ServerUnavailableException e = new ServerUnavailableException(DisplayName);
                e.Data.Add(nameof(e.Source), OfflineSource.DCOM);
                throw e;
            }
            var CertRequest = new CCertRequest();

            try {
                Int32 index = (Int32)CertRequest.GetCAProperty(ConfigString, CertAdmConstants.CrPropCaxchgcertcount, 0, 1, 0) - 1;
                if (index >= 0)
                {
                    String Base64 = (String)CertRequest.GetCAProperty(ConfigString, CertAdmConstants.CrPropCaxchgcert, index, 3, 1);
                    return(new X509Certificate2(Convert.FromBase64String(Base64)));
                }
                throw new Exception(String.Format(Error.E_XCHGUNAVAILABLE, DisplayName));
            } catch (Exception e) {
                throw Error.ComExceptionHandler(e);
            } finally {
                CryptographyUtils.ReleaseCom(CertRequest);
            }
        }
예제 #9
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);
            }
        }
예제 #10
0
        //get the certifacte status from the ca
        public int retrieveStatus(int requestID, string hostname)
        {
            int          iDisposition;
            string       strCAConfig;
            CCertConfig  objCertConfig  = new CCertConfig();
            CCertRequest objCertRequest = new CCertRequest();

            try
            {
                SqlLite sql = new SqlLite();
                /*Cheking if host name and req is belong to each other*/
                if (sql.checkHostnameWithreqID(requestID, hostname))
                {
                    return(-6);
                }
                if (sql.checkcertFlag(requestID)) //checking if the client allreay consumed the certificate
                {
                    return(-3);
                }



                strCAConfig  = objCertConfig.GetConfig(CC_DEFAULTCONFIG);              //connect to the ca
                iDisposition = objCertRequest.RetrievePending(requestID, strCAConfig); //retrive the certifcate status  from the ca
                sql.updateTable(iDisposition, requestID);                              //updat certificate table with more information about the cert
                return(iDisposition);                                                  //return cert status
            }

            catch (Exception ex)
            {
                Console.Write(ex.Message);
                return(-2);
            }
        }
예제 #11
0
        //submit the request  that created in the createCertifcate to the CA
        public int SubmitRequest(string certrequest, string hostname)
        {
            CCertConfig  objCertConfig  = new CCertConfig();
            CCertRequest objCertRequest = new CCertRequest();
            // CCertAdmin objCertAdmin = new CCertAdmin();
            string strCAConfig;
            int    iDisposition;
            int    requestID;
            string errorStatus;

            try
            {
                strCAConfig  = objCertConfig.GetConfig(CC_DEFAULTCONFIG);                           //connect to the ca
                iDisposition = objCertRequest.Submit(CR_IN_BASE64, certrequest, null, strCAConfig); //submit the certiface request to the ca
                requestID    = objCertRequest.GetRequestId();                                       //get the requestid that was created -the certifacte is in pending status
                Database db = new Database();
                db.InsertToCertificateTable(hostname, iDisposition, requestID);                     //insert first certificate information
                //   objCertAdmin.ResubmitRequest(strCAConfig, requestID);
                return(requestID);                                                                  //return the reqid that was created for the certificate request in the pending queue
            }

            catch (Exception ex)
            {
                errorStatus = ex.Message;
                Database db = new Database();
                db.InsertToErrorMessageTable(hostname, 0, ex.Message, "SubmitRequest");//insert Error Message into The Error Table Log In The DataBase
                return(0);
            }
        }
예제 #12
0
        //get the issue Certificate from the ca
        public string GetCertificate(int requestID)
        {
            int      iDisposition;
            int      status = 0;
            string   strCAConfig;
            string   pstrCertificate;
            Database db = new Database();

            pstrCertificate = null;
            CCertConfig  objCertConfig  = new CCertConfig();
            CCertRequest objCertRequest = new CCertRequest();

            try
            {
                strCAConfig     = objCertConfig.GetConfig(CC_DEFAULTCONFIG);              //connect to the ca
                iDisposition    = objCertRequest.RetrievePending(requestID, strCAConfig); //getting certificate stauts must before getting the cert
                pstrCertificate = objCertRequest.GetCertificate(CR_OUT_BASE64);           //retrive the Certificate
                status          = db.UpdateCertificateInfo(pstrCertificate, requestID);   //update cert with more information
                if (status == 0)
                {
                    Certificate cert = new Certificate {
                        CertValue = pstrCertificate
                    };                                                                   //creatre cert with JSON type
                    string certJson = Newtonsoft.Json.JsonConvert.SerializeObject(cert); //creatre cert with JSON type
                    return(certJson);                                                    //return certificate
                }

                else
                {
                    return("error Update Certificate Table");
                }
            }

            catch (Exception ex)
            {
                db.InsertToErrorMessageTable("", requestID, ex.Message, "GetCertificate");//insert Error Message into The Error Table Log In The DataBase
                return("error" + ex.Message);
            }
        }
예제 #13
0
        public IEnumerable <Template> GetCaTemplates(string caServer)
        {
            var certRequest = new CCertRequest();
            var templates   = new List <Template>();

            var regex = new Regex(@"([A-Za-z]+)");
            var value = certRequest.GetCAProperty(caServer, 29, 0, 4, 0).ToString();
            var lines = Regex.Split(value, @"\n");

            foreach (var line in lines)
            {
                var match = regex.Match(line);
                if (match.Success)
                {
                    templates.Add(new Template {
                        Name = line
                    });
                }
            }

            return(templates);
        }
예제 #14
0
        void m_initialize(CertificateAuthority certificateAuthority)
        {
            if (!certificateAuthority.IsEnterprise)
            {
                throw new PlatformNotSupportedException();
            }
            if (!certificateAuthority.Ping())
            {
                var e = new ServerUnavailableException(certificateAuthority.DisplayName);
                e.Data.Add(nameof(e.Source), OfflineSource.DCOM);
                throw e;
            }
            Name         = certificateAuthority.Name;
            DisplayName  = certificateAuthority.DisplayName;
            ComputerName = certificateAuthority.ComputerName;
            version      = certificateAuthority.Version;
            sku          = certificateAuthority.Sku;
            configString = certificateAuthority.ConfigString;

            var    CertAdmin = new CCertRequest();
            String templates = (String)CertAdmin.GetCAProperty(certificateAuthority.ConfigString, CertAdmConstants.CrPropTemplates, 0, CertAdmConstants.ProptypeString, 0);
            var    toBeAdded = new List <CertificateTemplate>();

            if (templates != String.Empty)
            {
                String[] SplitString = { "\n" };
                String[] TempArray   = templates.Split(SplitString, StringSplitOptions.RemoveEmptyEntries);
                for (Int32 index = 0; index < TempArray.Length; index += 2)
                {
                    toBeAdded.Add(new CertificateTemplate("Name", TempArray[index]));
                }
                Templates = toBeAdded.ToArray();
            }
            else
            {
                Templates = new CertificateTemplate[0];
            }
        }
예제 #15
0
        /// <summary>
        /// Returns all CA certificates.
        /// </summary>
        /// <exception cref="UninitializedObjectException">
        /// Current object is not initialized.
        /// </exception>
        /// <exception cref="ServerUnavailableException">
        /// Current CA server could not be contacted via remote registry and RPC protocol.
        /// </exception>
        /// <returns>A collection of CA certificates.</returns>
        public X509Certificate2Collection GetCACerts()
        {
            if (String.IsNullOrEmpty(Name))
            {
                throw new UninitializedObjectException();
            }
            if (!Ping())
            {
                var e = new ServerUnavailableException(DisplayName);
                e.Data.Add(nameof(e.Source), OfflineSource.DCOM);
                throw e;
            }
            var   CertRequest = new CCertRequest();
            var   certs       = new X509Certificate2Collection();
            Int32 count       = (Int32)CertRequest.GetCAProperty(ConfigString, CertAdmConstants.CrPropCasigcertcount, 0, 1, 0);

            for (Int32 index = 0; index < count; index++)
            {
                certs.Add(new X509Certificate(Convert.FromBase64String((String)CertRequest.GetCAProperty(ConfigString, CertAdmConstants.CrPropCasigcert, index, 3, 1))));
            }
            CryptographyUtils.ReleaseCom(CertRequest);
            return(certs);
        }
예제 #16
0
        //get the certifacte status from the ca
        public int RetrieveRequestStatus(int requestID, string hostname)
        {
            int          iDisposition;
            string       strCAConfig;
            CCertConfig  objCertConfig  = new CCertConfig();
            CCertRequest objCertRequest = new CCertRequest();

            try
            {
                Database db = new Database();
                /*Cheking if host name and req is belong to each other*/

                if (db.CheckIfReqIDBelongToHost(requestID, hostname))
                {
                    return(-6);
                }
                if (db.CheckIfCertificateConsumed(requestID)) //checking if the client allreay consumed the certificate
                {
                    return(-3);
                }



                strCAConfig  = objCertConfig.GetConfig(CC_DEFAULTCONFIG);              //connect to the ca
                iDisposition = objCertRequest.RetrievePending(requestID, strCAConfig); //retrive the certifcate status  from the ca
                db.UpdateUnlockFlagAndStatus(iDisposition, requestID);                 //updat certificate table with more information about the cert
                return(iDisposition);                                                  //return cert status
            }

            catch (Exception ex)
            {
                Database db = new Database();
                db.InsertToErrorMessageTable(hostname, requestID, ex.Message, "RetrieveRequestStatus");//insert Error Message into The Error Table Log In The DataBase
                return(-2);
            }
        }
예제 #17
0
        private static void Enroll(string publicKeyAsPem, string username, string agentCertificate, string caConfig)
        {
            string argsKey  = agentCertificate;
            string argsUser = username;

            X509Store store = new X509Store("My", StoreLocation.CurrentUser);

            store.Open(OpenFlags.ReadOnly);

            publicKeyAsPem = string.Join("", publicKeyAsPem.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).Where(s => !s.StartsWith("--")));

            // Create a PKCS 10 inner request.
            CX509PublicKey pubKey = new CX509PublicKey();

            pubKey.InitializeFromEncodedPublicKeyInfo(publicKeyAsPem);

            CObjectId sha512 = new CObjectId();

            sha512.InitializeFromValue("2.16.840.1.101.3.4.2.3");

            CX509CertificateRequestPkcs10 pkcs10Req = new CX509CertificateRequestPkcs10();

            pkcs10Req.InitializeFromPublicKey(X509CertificateEnrollmentContext.ContextUser, pubKey, "");
            pkcs10Req.HashAlgorithm = sha512;

            string toSign = pkcs10Req.RawDataToBeSigned[EncodingType.XCN_CRYPT_STRING_HASHDATA];

            //using (YubikeyPivTool piv = new YubikeyPivTool())
            //{
            //    //piv.
            //}


            // Create a CMC outer request and initialize
            CX509CertificateRequestCmc cmcReq = new CX509CertificateRequestCmc();

            cmcReq.InitializeFromInnerRequestTemplateName(pkcs10Req, "SmartcardLogon");
            cmcReq.RequesterName = argsUser;

            CSignerCertificate signer = new CSignerCertificate();

            signer.Initialize(false, X509PrivateKeyVerify.VerifyNone, (EncodingType)0xc, argsKey);
            cmcReq.SignerCertificate = signer;

            // encode the request
            cmcReq.Encode();

            string strRequest = cmcReq.RawData[EncodingType.XCN_CRYPT_STRING_BASE64];

            CCertRequest objCertRequest = new CCertRequest();

            // Get CA config from UI
            string strCAConfig = caConfig;

            // Submit the request
            int iDisposition = objCertRequest.Submit(CR_IN_BASE64 | CR_IN_FORMATANY, strRequest, null, strCAConfig);

            // Check the submission status
            if (CR_DISP_ISSUED != iDisposition) // Not enrolled
            {
                string strDisposition = objCertRequest.GetDispositionMessage();

                if (CR_DISP_UNDER_SUBMISSION == iDisposition)
                {
                    Console.WriteLine("The submission is pending: " + strDisposition);
                    return;
                }

                Console.WriteLine("The submission failed: " + strDisposition);
                Console.WriteLine("Last status: " + objCertRequest.GetLastStatus());
                return;
            }

            // Get the certificate
            string strCert = objCertRequest.GetCertificate(CR_OUT_BASE64);

            string argsCrt = "tmp.crt";

            File.WriteAllText(argsCrt, "-----BEGIN CERTIFICATE-----\n" + strCert + "-----END CERTIFICATE-----\n");
        }
예제 #18
0
        public string SelectCA()
        {
            var certConfig  = new CCertConfig();
            var certRequest = new CCertRequest();

            try
            {
                // Get CA config from UI
                var caConfig = certConfig.GetConfig((int)CertificateConfiguration.CC_UIPICKCONFIG);

                if (string.IsNullOrWhiteSpace(caConfig))
                {
                    return(null);
                }

                // Get CA Connection string
                var ca = certConfig.GetField("Config");

                // Get CA Type
                var caType     = certRequest.GetCAProperty(caConfig, 10, 0, 1, 0).ToString();
                var caTypeText = "";
                switch (caType)
                {
                case "0":
                    caTypeText = "ENTERPRISE ROOT CA";
                    break;

                case "1":
                    caTypeText = "ENTERPRISE SUB CA";
                    break;

                case "3":
                    caTypeText = "STANDALONE ROOT CA";
                    break;

                case "4":
                    caTypeText = "STANDALONE SUB CA";
                    break;
                }

                return(ca);
            }
            catch (Exception ex)
            {
                string error = null;

                if (ex.HResult.ToString() == "-2147023673")
                {
                    error = "Closed By user";
                }
                else if (ex.HResult.ToString() == "-2147024637")
                {
                    error = "Can't find available Servers";
                }
                else
                {
                    error = ex.Message + " " + ex.HResult;
                }

                throw new Exception(error, ex);
            }
        }
예제 #19
0
        private void btn_savecer_Click(object sender, RoutedEventArgs e)
        {
            string caserver = txt_CAServer.Text;
            string dir = Directory.GetParent(Assembly.GetExecutingAssembly().Location).ToString();

            if (Certs.Count == 0)
            {
                MessageBox.Show("No Request(s) To Save");
                return;
            }

            foreach (Certificates c in Certs)
            {
                var objCertRequest = new CCertRequest();
                int reqid = Convert.ToInt32(c.ID);

                var iDisposition = objCertRequest.RetrievePending(reqid, caserver);
                if (Convert.ToInt32(iDisposition) == 3)
                {
                    string cert = objCertRequest.GetCertificate(0);
                    System.IO.File.WriteAllText(dir + @"\" + c.FQDN + ".cer", cert);

                    c.Status = "File Created!";
                }
            }
        }
예제 #20
0
        static void Main(string[] args)
        {
            if (args.Length != 5)
            {
                Console.WriteLine("Usage: Signer.exe [EnrollmentCertificateThumbprint] [BehalfOfUser] [PathToCSR] [OutputFileName] [CertificateTemplate]");
                return;
            }

            string argsKey     = args[0];
            string argsUser    = args[1];
            string argsCsr     = args[2];
            string argsCrt     = args[3];
            string argsCrtTmpl = args[4];

            string csr = string.Join("\n", File.ReadAllLines(argsCsr).Where(s => s.Length > 0 && !s.StartsWith("--")));

            // Create a PKCS 10 inner request.
            CX509CertificateRequestPkcs10 pkcs10Req = new CX509CertificateRequestPkcs10();

            pkcs10Req.InitializeDecode(csr);

            // Create a CMC outer request and initialize
            CX509CertificateRequestCmc cmcReq = new CX509CertificateRequestCmc();

            cmcReq.InitializeFromInnerRequestTemplateName(pkcs10Req, argsCrtTmpl);
            cmcReq.RequesterName = argsUser;

            CSignerCertificate signer = new CSignerCertificate();

            signer.Initialize(false, X509PrivateKeyVerify.VerifyNone, (EncodingType)0xc, argsKey);
            cmcReq.SignerCertificate = signer;

            // encode the request
            cmcReq.Encode();

            string strRequest = cmcReq.RawData[EncodingType.XCN_CRYPT_STRING_BASE64];

            CCertConfig  objCertConfig  = new CCertConfig();
            CCertRequest objCertRequest = new CCertRequest();

            // Get CA config from UI
            string strCAConfig = objCertConfig.GetConfig(CC_UIPICKCONFIG);

            // Submit the request
            int iDisposition = objCertRequest.Submit(CR_IN_BASE64 | CR_IN_FORMATANY, strRequest, null, strCAConfig);

            // Check the submission status
            if (CR_DISP_ISSUED != iDisposition) // Not enrolled
            {
                string strDisposition = objCertRequest.GetDispositionMessage();

                if (CR_DISP_UNDER_SUBMISSION == iDisposition)
                {
                    Console.WriteLine("The submission is pending: " + strDisposition);
                    return;
                }

                Console.WriteLine("The submission failed: " + strDisposition);
                Console.WriteLine("Last status: " + objCertRequest.GetLastStatus());
                return;
            }

            // Get the certificate
            string strCert = objCertRequest.GetCertificate(CR_OUT_BASE64);

            File.WriteAllText(argsCrt, "-----BEGIN CERTIFICATE-----\n" + strCert + "-----END CERTIFICATE-----\n");
        }
        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();
        }