private ObservableList <Act> GetPlatformsActions(bool ShowAll = false) { ObservableList <Act> Acts = new ObservableList <Act>(); AppDomain.CurrentDomain.Load("GingerCore"); AppDomain.CurrentDomain.Load("GingerCoreCommon"); AppDomain.CurrentDomain.Load("GingerCoreNET"); var ActTypes = new List <Type>(); foreach (Assembly GC in AppDomain.CurrentDomain.GetAssemblies().Where(assembly => assembly.GetName().Name.Contains("GingerCore"))) { var types = from type in GC.GetTypes() where type.IsSubclassOf(typeof(Act)) && type != typeof(ActWithoutDriver) select type; ActTypes.AddRange(types); } foreach (Type t in ActTypes) { Act a = (Act)Activator.CreateInstance(t); if (a.IsSelectableAction == false) { continue; } if (mContext.BusinessFlow.CurrentActivity == null) { return(null); } TargetApplication TA = (TargetApplication)(from x in mContext.BusinessFlow.TargetApplications where x.Name == mContext.BusinessFlow.CurrentActivity.TargetApplication select x).FirstOrDefault(); if (TA == null) { if (mContext.BusinessFlow.TargetApplications.Count == 1) { TA = (TargetApplication)mContext.BusinessFlow.TargetApplications.FirstOrDefault(); mContext.BusinessFlow.CurrentActivity.TargetApplication = TA.AppName; } else { Reporter.ToUser(eUserMsgKey.MissingActivityAppMapping); return(null); } } ApplicationPlatform AP = (from x in WorkSpace.Instance.Solution.ApplicationPlatforms where x.AppName == TA.AppName select x).FirstOrDefault(); if (AP != null) { if (a.Platforms.Contains(AP.Platform)) { //DO Act.GetSampleAct in base if ((Acts.Where(c => c.GetType() == a.GetType()).FirstOrDefault()) == null) { a.Description = a.ActionDescription; a.Active = true; Acts.Add(a); } } } } return(Acts); }
public QTPImportPage() { InitializeComponent(); //handles the basic display of the UFT Import dialog ResultsDataGrid.DataSourceList = new ObservableList <ConvertedCodeLine>(); SetActivitiesGridView(); eFilter mFilter = eFilter.AllLines; App.FillComboFromEnumVal(FilterComboBox, mFilter); //TODO: Clear the hardcode values UFTObjectRepositoryTextBox.Text = @"C:\RaviKethe\T-Mobile\TMO-POC-QTP\uVerse_OR.xml"; //""; ScriptFileTextBox.Text = @"C:\RaviKethe\T-Mobile\TMO-POC-QTP\Sc005_Original.txt"; //""; // InitCommonFunctionMappingUCGrid(); TargetApplication sTarget = new TargetApplication(); if (App.UserProfile.Solution != null) { sTarget.AppName = App.UserProfile.Solution.MainApplication.ToString(); sTarget.Selected = true; TargetApplicationsList.Add(sTarget); mBusinessFlow.TargetApplications = TargetApplicationsList; } }
public void SetTargetApplications() { //mBusinessFlow.TargetApplications.Clear(); //remove deleted for (int indx = 0; indx < mBusinessFlow.TargetApplications.Count; indx++) { if (mApplicationsPlatforms.Where(x => x.Selected && x.AppName == mBusinessFlow.TargetApplications[indx].Name).FirstOrDefault() == null) { mBusinessFlow.TargetApplications.RemoveAt(indx); indx--; } } //add new foreach (ApplicationPlatform TA in mApplicationsPlatforms.Where(x => x.Selected).ToList()) { if (mBusinessFlow.TargetApplications.Where(x => x.Name == TA.AppName).FirstOrDefault() == null) { TargetApplication tt = new TargetApplication(); tt.AppName = TA.AppName; tt.Selected = true; mBusinessFlow.TargetApplications.Add(tt); } } }
//Called when an existing process in the process list has closed. //Removes it from the process list and listbox. //Also deinitializes the TargetApplication instance. private void _processWatcher_ClosedProcess(Process process) { for (int i = 0; i < this._processList.Count; i++) { TargetApplication tap = this._processList[i]; if (tap.Process.Id == process.Id) { this._processList.RemoveAt(i); this.listBoxProcessList.Items.RemoveAt(i); i--; tap.Deinitialize(false); //Select another process, if available. //Prioritizes process above closing process, //if available. if (this.listBoxProcessList.Items.Count != 0) { int newIndex = i - 1; int index = i < 0 ? 0 : i; this.listBoxProcessList.SelectedIndex = index; } break; } } }
public static ServiceContainer SetupLightInjectContainer(TargetApplication targetApplication, ILogger logger = null) { using (var container = new ServiceContainer()) { container.Register <IConfiguration, Configuration>(); if (logger == null) { logger = Configuration.SetupLogger(); } container.Register(factory => logger); container.Register <IAcmeClientConfigurationService, AcmeClientConfigurationService>(); // Get an AcmeClient so we can create a new AcmeClientService using the initialized instance var acmeClientService = container.GetInstance <IAcmeClientConfigurationService>(); var acmeClient = acmeClientService.Configure(targetApplication); container.Register(factory => acmeClient); container.Register <IAcmeClientService, AcmeClientService>(); container.Register <ICertificateService, CertificateService>(); container.Register <IPlugin, DefaultPlugin>(); RegisterPlugins(container); return(container); } }
private void OKButton_Click(object sender, RoutedEventArgs e) { int SelectedPlatformCount = 0; mBusinessFlow.TargetApplications.Clear(); foreach (ApplicationPlatform TA in mApplicationsPlatforms) { if (TA.Selected) { TargetApplication tt = new TargetApplication(); tt.AppName = TA.AppName; tt.Selected = true; mBusinessFlow.TargetApplications.Add(tt); SelectedPlatformCount++; } } if (App.BusinessFlow == mBusinessFlow) { App.UpdateApplicationsAgentsMapping(); } if (SelectedPlatformCount > 0 || mApplicationsPlatforms.Count == 0) { _pageGenericWin.Close(); } else { Reporter.ToUser(eUserMsgKeys.BusinessFlowNeedTargetApplication); } }
public void Initialize() { var hostnames = new List <string> { "cork.nl", "www.cork.nl" }; TargetApplication = new TargetApplication { CertificatePassword = "******", Hostnames = hostnames }; var container = ContainerRegistration.SetupLightInjectContainer(TargetApplication); var configuration = container.GetInstance <IConfiguration>(); AcmeClientService = container.GetInstance <IAcmeClientService>(); CertificateService = container.GetInstance <ICertificateService>(); // Cleanup authorization files if they exist to make sure we start with a clean slate var basePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, TargetApplication.Hostnames.First()); var signerFile = Path.Combine(basePath, configuration.SignerFilename); var registrationFile = Path.Combine(basePath, configuration.RegistrationFilename); if (File.Exists(signerFile)) { File.Delete(signerFile); } if (File.Exists(registrationFile)) { File.Delete(registrationFile); } }
//Trigger the IncreaseIndex() method through our DLL, which triggers //the method within our selected TargetApplication process. private void buttonTriggerIncrease_Click(object sender, EventArgs e) { TargetApplication targetApplication = this.TargetApplication; if (targetApplication != null) { targetApplication.TriggerIncreaseIndex(); } }
//Change the amount the index is increased with each trigger. //This applies to both the force-trigger via the Trigger button, and //also TargetApplication's increase function from pressing enter. private void numericUpDownIncreaseIndex_ValueChanged(object sender, EventArgs e) { TargetApplication targetApplication = this.TargetApplication; if (targetApplication != null) { targetApplication.IncreaseIndex = (int)this.numericUpDownIncreaseIndex.Value; } }
//Initialize the TargetApplication instance that gets selected. private void listBoxProcessList_SelectedIndexChanged(object sender, EventArgs e) { TargetApplication targetApplication = this.TargetApplication; if (targetApplication != null) { targetApplication.Initialize(); targetApplication.IncreaseIndex = (int)this.numericUpDownIncreaseIndex.Value; } }
public string GetBaseOutPutPath(TargetApplication targetApplication) { var acmeServerBaseUri = GetAcmeServerBaseUri(targetApplication).Host; var basePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, acmeServerBaseUri, targetApplication.Hostnames.First()); if (Directory.Exists(basePath) == false) { Directory.CreateDirectory(basePath); } return(basePath); }
//Called when a new process instance of TargetApplication is found. //Adds it to the process list and listbox. private void _processWatcher_NewProcess(Process process) { TargetApplication tap = new TargetApplication(process); this._processList.Add(tap); this.listBoxProcessList.Items.Add(tap); //Select the first process by default. if (this.listBoxProcessList.Items.Count == 1) { this.listBoxProcessList.SelectedIndex = 0; } }
private void ImportExternalBuinessFlow(object sender, System.Windows.RoutedEventArgs e) { BusinessFlow importedBF = null; //open dialog for selecting the BF file System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog(); dlg.DefaultExt = ".Ginger.BusinessFlow.xml"; dlg.Filter = "Ginger Business Flow File|*.Ginger.BusinessFlow.xml"; if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) { try { //copy to Solution Business Flow folder string importedBFpath = System.IO.Path.Combine(Path, System.IO.Path.GetFileName(dlg.FileName)); File.Copy(dlg.FileName, importedBFpath, false); //load it to object importedBF = (BusinessFlow)RepositoryItem.LoadFromFile(typeof(BusinessFlow), importedBFpath); //customize the imported BF importedBF.Guid = Guid.NewGuid(); for (int i = 0; i < importedBF.TargetApplications.Count; i++) { if (App.UserProfile.Solution.ApplicationPlatforms.Where(x => x.AppName == importedBF.TargetApplications[i].AppName).FirstOrDefault() == null) { importedBF.TargetApplications.RemoveAt(i);//No such Application so Delete it i--; } } if (importedBF.TargetApplications.Count == 0) { TargetApplication ta = new TargetApplication(); ta.AppName = App.UserProfile.Solution.ApplicationPlatforms[0].AppName; importedBF.TargetApplications.Add(ta); } importedBF.Save(); //add it to cache & tree App.LocalRepository.AddItemToCache(importedBF); BusinessFlowTreeItem importedBFTI = new BusinessFlowTreeItem(); importedBFTI.BusinessFlow = importedBF; mTreeView.Tree.AddChildItemAndSelect(this, importedBFTI); } catch (Exception ex) { Reporter.ToUser(eUserMsgKeys.StaticErrorMessage, "Failed to copy and load the selected " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + " file." + System.Environment.NewLine + "Error: " + System.Environment.NewLine + ex.Message); return; } } }
//Send the text from the textBoxPrintString control to the DLL, //which calls the printf() function to print the text into the //TargetApplication's console. private void SendInput() { if (!string.IsNullOrWhiteSpace(this.textBoxPrintString.Text)) { TargetApplication targetApplication = this.TargetApplication; if (targetApplication != null) { targetApplication.PrintString(this.textBoxPrintString.Text); //Clear the textbox after sending. this.textBoxPrintString.Clear(); } } }
public void SetTargetApplications() { mBusinessFlow.TargetApplications.Clear(); foreach (ApplicationPlatform TA in mApplicationsPlatforms) { TargetApplication tt = new TargetApplication(); if (TA.Selected) { tt.AppName = TA.AppName; tt.Selected = true; mBusinessFlow.TargetApplications.Add(tt); } } }
private void ImportExternalBuinessFlow(object sender, System.Windows.RoutedEventArgs e) { BusinessFlow importedBF = null; //open dialog for selecting the BF file if (General.SetupBrowseFile(new System.Windows.Forms.OpenFileDialog() { DefaultExt = ".Ginger.BusinessFlow.xml", Filter = "Ginger Business Flow File|*.Ginger.BusinessFlow.xml" }, false) is string fileName) { try { //copy to Solution Business Flow folder string importedBFpath = System.IO.Path.Combine(mBusFlowsFolder.FolderFullPath, System.IO.Path.GetFileName(fileName)); File.Copy(fileName, importedBFpath, false); //load it to object importedBF = (BusinessFlow)RepositoryItem.LoadFromFile(typeof(BusinessFlow), importedBFpath); //customize the imported BF importedBF.Guid = Guid.NewGuid(); for (int i = 0; i < importedBF.TargetApplications.Count; i++) { if (WorkSpace.Instance.Solution.ApplicationPlatforms.Where(x => x.AppName == importedBF.TargetApplications[i].Name).FirstOrDefault() == null) { importedBF.TargetApplications.RemoveAt(i);//No such Application so Delete it i--; } } if (importedBF.TargetApplications.Count == 0) { TargetApplication ta = new TargetApplication(); ta.AppName = WorkSpace.Instance.Solution.ApplicationPlatforms[0].AppName; importedBF.TargetApplications.Add(ta); } WorkSpace.Instance.SolutionRepository.SaveRepositoryItem(importedBF); mBusFlowsFolder.AddRepositoryItem(importedBF); } catch (Exception ex) { Reporter.ToUser(eUserMsgKey.StaticErrorMessage, "Failed to copy and load the selected " + GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + " file." + System.Environment.NewLine + "Error: " + System.Environment.NewLine + ex.Message); return; } } }
public AcmeClient Configure(TargetApplication targetApplication) { var contacts = NormalizeContacts(); var signer = new RS256Signer(); var basePath = _configuration.GetBaseOutPutPath(targetApplication); ConfigureSigner(signer, basePath); var acmeServerBaseUri = _configuration.GetAcmeServerBaseUri(targetApplication); var acmeClient = new AcmeClient(acmeServerBaseUri, new AcmeServerDirectory(), signer); acmeClient.Init(); acmeClient.GetDirectory(saveRelative: true); ProcessRegistration(acmeClient, contacts.ToArray(), basePath); return(acmeClient); }
public IEnumerable <AuthorizationState> RequestVerificationChallenge(TargetApplication website) { var authorizationStates = new List <AuthorizationState>(); foreach (var hostname in website.Hostnames) { _logger.Information("Authorizing hostname {hostname} using challenge type {CHALLENGE_TYPE_HTTP}", hostname, AcmeProtocol.CHALLENGE_TYPE_HTTP); var authorizationState = _acmeClient.AuthorizeIdentifier(hostname); _logger.Information("Authorization status for {hostname} is now {state}", hostname, authorizationState.Status); authorizationStates.Add(authorizationState); } return(authorizationStates); }
public AuthorizationState HandleVerificationChallenge(TargetApplication application, AuthorizationState authorizationState) { var challenge = _acmeClient.DecodeChallenge(authorizationState, AcmeProtocol.CHALLENGE_TYPE_HTTP); var httpChallenge = (HttpChallenge)challenge.Challenge; if (httpChallenge == null) { _logger.Error("Could not decode challenge for {hostname} using the {protocol} protocol", authorizationState.Identifier, AcmeProtocol.CHALLENGE_TYPE_HTTP); return(null); } _logger.Information("Expecting response on URL {responseUrl}", httpChallenge.FileUrl); CreateChallengeResponse(httpChallenge); CheckChallengeResponse(httpChallenge); return(_acmeClientService.RequestChallengeVerification(authorizationState, challenge)); }
private void SetGridView() { GridViewDef view = new GridViewDef(GridViewDef.DefaultViewName); view.GridColsView = new ObservableList <GridColView>(); view.GridColsView.Add(new GridColView() { Field = "Selected", WidthWeight = 20, StyleType = GridColView.eGridColStyleType.CheckBox }); view.GridColsView.Add(new GridColView() { Field = "AppName", Header = "Application Name", WidthWeight = 50, ReadOnly = true, BindingMode = BindingMode.OneWay }); view.GridColsView.Add(new GridColView() { Field = "Platform", Header = "Platform", WidthWeight = 30, ReadOnly = true, BindingMode = BindingMode.OneWay }); AppsGrid.SetAllColumnsDefaultView(view); AppsGrid.InitViewItems(); foreach (ApplicationPlatform AP in WorkSpace.Instance.Solution.ApplicationPlatforms) { ApplicationPlatform AP1 = new ApplicationPlatform(); AP1.AppName = AP.AppName; AP1.Platform = AP.Platform; // If this App was selected before then mark it TargetApplication APS = (TargetApplication)(from x in mBusinessFlow.TargetApplications where x.Name == AP.AppName select x).FirstOrDefault(); if (APS != null) { AP1.Selected = true; } mApplicationsPlatforms.Add(AP1); } AppsGrid.DataSourceList = mApplicationsPlatforms; }
public QTPImportPage() { InitializeComponent(); //handles the basic display of the UFT Import dialog ResultsDataGrid.DataSourceList = new ObservableList <ConvertedCodeLine>(); SetActivitiesGridView(); eFilter mFilter = eFilter.AllLines; GingerCore.General.FillComboFromEnumObj(FilterComboBox, mFilter); InitCommonFunctionMappingUCGrid(); TargetApplication sTarget = new TargetApplication(); if (WorkSpace.Instance.Solution != null) { sTarget.AppName = WorkSpace.Instance.Solution.MainApplication.ToString(); sTarget.Selected = true; TargetApplicationsList.Add(sTarget); mBusinessFlow.TargetApplications = TargetApplicationsList; } }
public void ConfigureCertificate(TargetApplication application, string certificatePath) { }
private string GetIssuerCertificate(CertificateRequest certificate, IPkiTool cp, string certificateFolder, TargetApplication targetApplication) { var linksEnum = certificate.Links; if (linksEnum == null) { return(null); } var links = new LinkCollection(linksEnum); var upLink = links.GetFirstOrDefault("up"); if (upLink == null) { return(null); } var temporaryFileName = Path.GetTempFileName(); try { using (var web = new WebClient()) { var acmeServerBaseUri = _configuration.GetAcmeServerBaseUri(targetApplication); var uri = new Uri(acmeServerBaseUri, upLink.Uri); web.DownloadFile(uri, temporaryFileName); } var cacert = new X509Certificate2(temporaryFileName); var sernum = cacert.GetSerialNumberString(); var cacertDerFile = Path.Combine(certificateFolder, $"ca-{sernum}-crt.der"); var cacertPemFile = Path.Combine(certificateFolder, $"ca-{sernum}-crt.pem"); if (!File.Exists(cacertDerFile)) { File.Copy(temporaryFileName, cacertDerFile, true); } _logger.Information("Saving issuer certificate to {cacertPemFile}", cacertPemFile); if (File.Exists(cacertPemFile)) { return(cacertPemFile); } using (FileStream source = new FileStream(cacertDerFile, FileMode.Open), target = new FileStream(cacertPemFile, FileMode.Create)) { var caCrt = cp.ImportCertificate(EncodingFormat.DER, source); cp.ExportCertificate(caCrt, EncodingFormat.PEM, target); } return(cacertPemFile); } finally { if (File.Exists(temporaryFileName)) { File.Delete(temporaryFileName); } } }
public void Setup(TargetApplication application) { }
public SecureStoreContainer(TargetApplication app, SecureStoreProvider provider) { _app = app; _provider = provider; }
public IEnumerable <AuthorizationState> RequestVerificationChallenge(TargetApplication application) { return(_acmeClientService.RequestVerificationChallenge(application)); }
private void AddPropertyToRatedLists(string key, RiskRating rating, TargetApplication target) { if (m_list.ContainsKey(key)) { switch (rating) { case RiskRating.Low: case RiskRating.Medium: case RiskRating.High: case RiskRating.Rated: m_RatedRisk.Add(key, target); m_riskRatedProperties.Add(key, rating); break; case RiskRating.Exclusion: m_ExclusionRatedRisk.Add(key, target); break; case RiskRating.None: break; default: { ErrorMessage errorMessage = new ErrorMessage("UNEXPECTED_RISK_RATING", "Workshare.Policy.Actions.Properties.LanguageResources", Assembly.GetExecutingAssembly()); Logger.LogError(errorMessage.LogString); throw new CleanUserActionException(errorMessage.DisplayString); } } } else { ErrorMessage errorMessage = new ErrorMessage("CLEANUSERACTIONPROPERTY", "Workshare.Policy.Actions.Properties.LanguageResources", Assembly.GetExecutingAssembly()); Logger.LogError(errorMessage.LogString); // Don't throw an exception currently because binary clean doesn't have all properties? //str = Utilities.CultureSpecificString.CurrentResourceString("CLEANUSERACTIONPROPERTY", "Workshare.Policy.Actions.Properties.LanguageResources", Assembly.GetExecutingAssembly()); //str = string.Format(CultureInfo.CurrentCulture, str, key); //throw new CleanUserActionException(str); } }
public void Properties() { ITargetApplication target = new TargetApplication(); Assert.IsNull(target.Name); }
private void AddPropertyToRatedLists(string key, RiskRating rating, TargetApplication target) { if (m_list.ContainsKey(key)) { switch (rating) { case RiskRating.Low: case RiskRating.Medium: case RiskRating.High: case RiskRating.Rated: m_RatedRisk.Add(key, target); m_riskRatedProperties.Add(key, rating); break; case RiskRating.None: break; default: { ErrorMessage errorMessage = new ErrorMessage("UNEXPECTED_RISK_RATING", "Workshare.Policy.Actions.Properties.LanguageResources", Assembly.GetExecutingAssembly()); Logger.LogError(errorMessage.LogString); throw new Exception(errorMessage.DisplayString); } } } else { ErrorMessage errorMessage = new ErrorMessage("PDFCLEANUSERACTIONPROPERTY", "Workshare.Policy.Actions.Properties.LanguageResources", Assembly.GetExecutingAssembly()); Logger.LogError(errorMessage.LogString); } }
public string GetCertificate(TargetApplication application) { return(_certificateService.GetCertificate(application)); }
public void TargetFile() { var target = new TargetApplication(); Assert.IsNull(target.TargetFile); }
public string GetCertificate(TargetApplication targetApplication) { using (var pkiTool = PkiToolExtManager.GetPkiTool("BouncyCastle")) { var rsaKeyParams = new RsaPrivateKeyParams(); var rsaKeys = pkiTool.GeneratePrivateKey(rsaKeyParams); var certificateName = targetApplication.Hostnames.First(); var baseOutPutPath = _configuration.GetBaseOutPutPath(targetApplication); var certificateFolder = Path.Combine(baseOutPutPath, $"{DateTime.Now:yyyyMMdd_HHmmss}"); if (Directory.Exists(certificateFolder) == false) { Directory.CreateDirectory(certificateFolder); } var csrDetails = new CsrDetails { CommonName = certificateName, AlternativeNames = targetApplication.Hostnames, }; var certificateSigningRequest = pkiTool.GenerateCsr( new CsrParams { Details = csrDetails }, rsaKeys, Crt.MessageDigest.SHA256); byte[] certificateSigningRequestBytes; using (var bs = new MemoryStream()) { pkiTool.ExportCsr(certificateSigningRequest, EncodingFormat.DER, bs); certificateSigningRequestBytes = bs.ToArray(); } var certificateSigningRequestBytesBase64 = JwsHelper.Base64UrlEncode(certificateSigningRequestBytes); _logger.Information("Requesting a certificate"); var certificateRequest = _acmeClient.RequestCertificate(certificateSigningRequestBytesBase64); _logger.Debug("Result of certificate request {certificateRequest}", certificateRequest); _logger.Information("Certificate request status is {statusCode}", certificateRequest.StatusCode); if (certificateRequest.StatusCode == HttpStatusCode.Created) { var keyGenFile = Path.Combine(certificateFolder, $"{certificateName}-gen-key.json"); var keyPemFile = Path.Combine(certificateFolder, $"{certificateName}-key.pem"); var csrGenFile = Path.Combine(certificateFolder, $"{certificateName}-gen-csr.json"); var csrPemFile = Path.Combine(certificateFolder, $"{certificateName}-csr.pem"); var crtDerFile = Path.Combine(certificateFolder, $"{certificateName}-crt.der"); var crtPemFile = Path.Combine(certificateFolder, $"{certificateName}-crt.pem"); var chainPemFile = Path.Combine(certificateFolder, $"{certificateName}-chain.pem"); using (var fileStream = new FileStream(keyGenFile, FileMode.Create)) pkiTool.SavePrivateKey(rsaKeys, fileStream); using (var fileStream = new FileStream(keyPemFile, FileMode.Create)) pkiTool.ExportPrivateKey(rsaKeys, EncodingFormat.PEM, fileStream); using (var fileStream = new FileStream(csrGenFile, FileMode.Create)) pkiTool.SaveCsr(certificateSigningRequest, fileStream); using (var fileStream = new FileStream(csrPemFile, FileMode.Create)) pkiTool.ExportCsr(certificateSigningRequest, EncodingFormat.PEM, fileStream); _logger.Information("Saving certificate to {crtDerFile}", crtDerFile); using (var file = File.Create(crtDerFile)) certificateRequest.SaveCertificate(file); Crt crt; using (FileStream source = new FileStream(crtDerFile, FileMode.Open), target = new FileStream(crtPemFile, FileMode.Create)) { crt = pkiTool.ImportCertificate(EncodingFormat.DER, source); pkiTool.ExportCertificate(crt, EncodingFormat.PEM, target); } var issuerCertificate = GetIssuerCertificate(certificateRequest, pkiTool, certificateFolder, targetApplication); using (FileStream intermediate = new FileStream(issuerCertificate, FileMode.Open), certificate = new FileStream(crtPemFile, FileMode.Open), chain = new FileStream(chainPemFile, FileMode.Create)) { certificate.CopyTo(chain); intermediate.CopyTo(chain); } var crtPfxFile = Path.Combine(certificateFolder, $"{targetApplication.Hostnames.First()}.pfx"); _logger.Information("Saving certificate for hostname {host} and alternative hostnames {@altHostNames} to {crtPfxFile}", targetApplication.Hostnames.First(), targetApplication.Hostnames.Skip(1), crtPfxFile); using (FileStream source = new FileStream(issuerCertificate, FileMode.Open), target = new FileStream(crtPfxFile, FileMode.Create)) { try { var importCertificate = pkiTool.ImportCertificate(EncodingFormat.PEM, source); pkiTool.ExportArchive(rsaKeys, new[] { crt, importCertificate }, ArchiveFormat.PKCS12, target, targetApplication.CertificatePassword); } catch (Exception ex) { _logger.Error("Error exporting archive {@ex}", ex); } } pkiTool.Dispose(); return(crtPfxFile); } _logger.Error("Request status is {statusCode}", certificateRequest.StatusCode); throw new Exception($"Request status = {certificateRequest.StatusCode}"); } }