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); }
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); } } } }
/// <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> /// 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); } }
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); }
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); }
//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); } }
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"); }
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"); }
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!"; } } }
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(); }