private async Task listCertificatesWithKey() { var certificates = new List <PKCertificateWithKey>(); var modules = getPkcs11Modules(); await Task.Run(() => { // list PKCS#11 certificates if any module set if (modules.Any()) { using (var p11Store = Pkcs11CertificateStore.Load(modules, new P11LoginProvider(true))) { certificates.AddRange(p11Store.GetCertificatesWithKey()); } } // get all windows certificates that are not yet listed certificates.AddRange(WindowsCertificateStore.LoadPersonalCurrentUser().GetCertificatesWithKey() .FindAll(winc => !certificates.Select(c => c.Certificate).Contains(winc.Certificate))); }); // clear any previous list CertificatesCB.Items.Clear(); // populate certificates.OrderBy(c => c.Certificate.SubjectDisplayName).ToList().ForEach(c => CertificatesCB.Items.Add(new ComboCertificate(c.Certificate))); addLog($"{CertificatesCB.Items.Count} Certificates found"); if (CertificatesCB.Items.Count > 0) { CertificatesCB.SelectedItem = CertificatesCB.Items[0]; } }
private static int RunListAndReturnExitCode(ListOptions opts) { var certificates = WindowsCertificateStore.LoadPersonalCurrentUser().GetCertificatesWithKey().Where(c => c.Certificate.PkiBrazil.CPF != null).ToList(); for (int i = 0; i < certificates.Count; i++) { Console.WriteLine($"{i} - {certificates[i].Certificate.SubjectDisplayName}"); } return(0); }
public void RefreshCertificates() { var originallySelected = this.SelectedCertificate; Certificates.Clear(); var certStore = WindowsCertificateStore.LoadPersonalCurrentUser(); certStore.GetCertificatesWithKey().ForEach(c => Certificates.Add(new CertificateItem(c))); if (originallySelected != null) { SelectedCertificate = Certificates.FirstOrDefault(c => c.CertificateWithKey.Certificate.Equals(originallySelected.CertificateWithKey.Certificate)); } }
static void Main(string[] args) { // This is a TRIAL token. It will expire at 31/08/2020. PkiConfig.LoadLicense(Convert.FromBase64String("AxAAIIy8jc59Q0q95BZrL57K5hEAUEtJIFN1aXRlIFNhbXBsZXMIAAD0Ze31HdgICACAXwryrU7YCAAAAAAAAAQAfwAAAAABL2+ls7EW5LHD/tEetd49d0JpmU7pXEjhH0pU1ZSp5qjvKxL8c8PZz6ODTf68+lfQtXkKaRlQH6hu7VTSU3fvhCmZovDB5ruKqJPn+MQRDBbS8Wkr/meVo9LBS+3NFOky+EY43ebFoFxTbVZl2lCjb0DuskJiZGuHOBJ1v2XpGdKCmh1c1LmMvpc+OPegzNuMCXoEzSN9DdRtKnDzRxvOnvPglCX9+oV89LWsmVzonRp1a+tluqa8Ron9pFdHI9cWBElcXpmwXbKbmP0Sy5yYbYpE+rYsNgD5sV/FwF8uOxGWA0/mRWLZlO3OcGWoYo7qBBDmCUApAcRmZR3tXqhELQ==")); var connection = new ConnectionBuilder() .WithLogging() .Build(); // "List Certificates" operation. connection.On <string, List <CertificateModel> >("list-certs", _ => { var store = WindowsCertificateStore.LoadPersonalCurrentUser(); return(store.GetCertificatesWithKey().Select(c => new CertificateModel(c.Certificate)).ToList()); }); // "Sign a PDF" operation. connection.On <SignatureRequestModel, string>("sign-pdf", request => { var signer = new PadesSigner(); var store = WindowsCertificateStore.LoadPersonalCurrentUser(); var signingCert = store.GetCertificatesWithKey().First(c => c.Certificate.ThumbprintSHA256.SequenceEqual(request.CertThumb)); signer.SetSigningCertificate(signingCert); signer.SetPdfToSign(request.FileToSign); var trustArbitrator = new LinkedTrustArbitrator(TrustArbitrators.PkiBrazil, TrustArbitrators.Windows); // For development purposes, we also trust in Lacuna Software's test certificates. var lacunaRoot = Lacuna.Pki.PKCertificate.Decode(Convert.FromBase64String("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")); // COMMENT the line below before production release trustArbitrator.Add(new TrustedRoots(lacunaRoot)); signer.SetPolicy(PadesPoliciesForGeneration.GetPadesBasic(trustArbitrator)); signer.ComputeSignature(); byte[] signedPdf = signer.GetPadesSignature(); var tempLocation = Path.GetTempFileName(); File.WriteAllBytes(tempLocation, signedPdf); return(tempLocation); }); // Acknowledges that the connection is running. connection.On <string, string>("ping", argument => "pong"); // wait for incoming requests connection.Listen(); }
public void RefreshCertificates() { var originallySelected = this.SelectedCertificate; Certificates.Clear(); var certStore = WindowsCertificateStore.LoadPersonalCurrentUser(); foreach (var item in certStore.GetCertificatesWithKey().Select(c => new CertificateItem(c)).OrderBy(i => i.ToString())) { Certificates.Add(item); } if (originallySelected != null) { SelectedCertificate = Certificates.FirstOrDefault(c => c.CertificateWithKey.Certificate.Equals(originallySelected.CertificateWithKey.Certificate)); } }
private static int RunSignAndReturnExitCode(SignOptions opts) { var certificates = WindowsCertificateStore.LoadPersonalCurrentUser().GetCertificatesWithKey().Where(c => c.Certificate.PkiBrazil.CPF != null).ToList(); var certificate = certificates[opts.Certificate]; var fileName = opts.InputFile; using var stream = File.OpenRead(fileName); var digestAlgorithm = DigestAlgorithm.SHA256; var digest = digestAlgorithm.ComputeHash(stream); var signer = new CadesSigner(); signer.SetSigningCertificate(certificate); signer.SetPolicy(CadesPoliciesForGeneration.GetPkiBrazilAdrBasica()); signer.SetEncapsulatedContent(false); signer.SetDataDigestToSign(digestAlgorithm, digest); signer.ComputeSignature(); var cades = signer.GetSignature(); File.WriteAllBytes(opts.SignedFile, cades); stream.Close(); return(0); }
private async void signButtonClick(object sender, RoutedEventArgs e) { //var progressDialog = await this.ShowProgressAsync("Please wait...", "Signing"); Pkcs11CertificateStore p11Store = null; addLog($"Signature process begin"); progressBar.Value = 10; try { var signatureStarter = new PadesSignatureStarter(restPkiClient) { // Set the unit of measurement used to edit the pdf marks and visual representations MeasurementUnits = PadesMeasurementUnits.Centimeters, // Set the signature policy SignaturePolicyId = StandardPadesSignaturePolicies.Basic, // Set a SecurityContext to be used to determine trust in the certificate chain SecurityContextId = Guid.Parse("803517ad-3bbc-4169-b085-60053a8f6dbf"), //SecurityContextId =StandardSecurityContexts.PkiBrazil, // Note: this SecurityContext above accept unsecured certificates. You can create custom security context on the Rest PKI website. // Set a visual representation for the signature VisualRepresentation = createVisualRepresentation() }; progressBar.Value = 15; // If the user was redirected here by UploadController (signature with file uploaded by user), the "userfile" URL argument // will contain the filename under the "App_Data" folder. Otherwise (signature with server file), we'll sign a sample // document. if (string.IsNullOrEmpty(FileToSign)) { // Set the PDF to be signed as a byte array signatureStarter.SetPdfToSign(Signer.Resources.SampleDocument); } else { // Set the path of the file to be signed addLog($"file size {(new FileInfo(FileToSign).Length / 1024.0).ToString("0.00")} KBytes"); signatureStarter.SetPdfToSign(FileToSign); } /* * Optionally, add marks to the PDF before signing. These differ from the signature visual representation in that * they are actually changes done to the document prior to signing, not binded to any signature. Therefore, any number * of marks can be added, for instance one per page, whereas there can only be one visual representation per signature. * However, since the marks are in reality changes to the PDF, they can only be added to documents which have no previous * signatures, otherwise such signatures would be made invalid by the changes to the document (see property * PadesSignatureStarter.BypassMarksIfSigned). This problem does not occurr with signature visual representations. * * We have encapsulated this code in a method to include several possibilities depending on the argument passed. * Experiment changing the argument to see different examples of PDF marks. Once you decide which is best for your case, * you can place the code directly here. */ signatureStarter.PdfMarks.Add(PadesVisualElements.GetPdfMark(1)); // Call the StartWithWebPki() method, which initiates the signature. This yields the token, a 43-character // case-sensitive URL-safe string, which identifies this signature process. We'll use this value to call the // signWithRestPki() method on the Web PKI component (see javascript on the view) and also to complete the signature // on the POST action below (this should not be mistaken with the API access token). // Find selected certificate with key // -------------------------------------------------------------- PKCertificateWithKey certWithKey = null; var selectedThumbprint = (CertificatesCB.SelectedItem as ComboCertificate).Certificate.ThumbprintSHA256; p11Store = Pkcs11CertificateStore.Load(getPkcs11Modules(), new P11LoginProvider()); // search on pkcs11 store if (findCertificate(p11Store.GetCertificatesWithKey(), selectedThumbprint, out certWithKey)) { } else if (findCertificate(WindowsCertificateStore.LoadPersonalCurrentUser().GetCertificatesWithKey(), selectedThumbprint, out certWithKey)) { } else { throw new Exception("Selected certificate not found"); } // -------------------------------------------------------------- signatureStarter.SetSignerCertificate(certWithKey.Certificate.EncodedValue); progressBar.Value = 30; addLog($"Step 1: Start Signature"); var sw = Stopwatch.StartNew(); Token = await signatureStarter.StartAsync(); sw.Stop(); addLog($"Step 1: Signature Started, elapsed {sw.Elapsed.TotalSeconds:N1}s"); progressBar.Value = 50; addLog($"Signing with {certWithKey.Certificate.SubjectDisplayName}"); var signature = certWithKey.SignData(Lacuna.Pki.DigestAlgorithm.GetInstanceByOid(Token.DigestAlgorithmOid), Token.ToSignData); addLog($"Signed"); progressBar.Value = 70; var signatureFinisher = new PadesSignatureFinisher2(restPkiClient) { Token = Token.Token, Signature = signature }; sw = Stopwatch.StartNew(); // Call the Finish() method, which finalizes the signature process and returns a SignatureResult object addLog($"Step 2: Finish Signature"); var signatureResult = await signatureFinisher.FinishAsync(); sw.Stop(); addLog($"Step 2: Signature Finished, elapsed {sw.Elapsed.TotalSeconds:N1}s"); SignedFile = System.IO.Path.Combine(Path.GetDirectoryName(FileToSign), Path.GetFileNameWithoutExtension(FileToSign) + "-signed" + Path.GetExtension(FileToSign)); signatureResult.WriteToFile(SignedFile); //BusyIndicator.IsBusy = false; progressBar.Value = 100; OpenFileSignedBt.IsEnabled = true; addLog($"File signed: {SignedFile}"); } catch (Exception ex) { addLog(ex.ToString()); } finally { if (p11Store != null) { p11Store.Dispose(); } } progressBar.Value = 0; }
public void ConfigureCertificateStoreProvider() { ICertificateOptions options = Environment.Host.ApplicationBuilder.ApplicationServices.GetRequiredService <ICertificateOptions>(); ICertificateStoreProvider storeProvider = Environment.Host.ApplicationBuilder.ApplicationServices.GetRequiredService <ICertificateStoreProvider>(); IWebServerVersion versionProvider = Environment.Host.ApplicationBuilder.ApplicationServices.GetService <IWebServerVersion>(); const string webHosting = "WebHosting"; const string my = "My"; // // My if (!storeProvider.Stores.Any(s => s.Name.Equals(my, System.StringComparison.OrdinalIgnoreCase)) && WindowsCertificateStore.Exists(my)) { storeProvider.AddStore(new WindowsCertificateStore(my, new string[] { "read" })); } if (versionProvider?.Version != null && versionProvider.Version >= new System.Version(8, 0)) { // // WebHosting Certificate Store was not introduced until IIS 8.0 if (!storeProvider.Stores.Any(s => s.Name.Equals(webHosting, System.StringComparison.OrdinalIgnoreCase)) && WindowsCertificateStore.Exists(webHosting)) { storeProvider.AddStore(new WindowsCertificateStore(webHosting, new string[] { "read" })); } } }
static void process(Options options) { PkiConfig.LoadLicense(Convert.FromBase64String(LicenseBase64)); var isTest = options.Test > 0; var testCount = options.Test; var documentsInputDir = options.SourceDir; var signedDocumentsOutputDir = options.DestinationDir; if (isTest) { Util.CheckTestDirectories(documentsInputDir, signedDocumentsOutputDir); DeleteFiles(documentsInputDir, signedDocumentsOutputDir); PdfGenerate(testCount, documentsInputDir); } else { if (!Directory.Exists(documentsInputDir) && string.IsNullOrWhiteSpace(options.File)) { Console.WriteLine($"Error! The directory was not found: {documentsInputDir}"); return; } if (!Directory.Exists(signedDocumentsOutputDir) && string.IsNullOrWhiteSpace(options.File)) { Directory.CreateDirectory(signedDocumentsOutputDir); } Console.WriteLine(); } // Signer certificate PKCertificateWithKey cert = null; var store = Pkcs11CertificateStore.Load("eTPKCS11.dll", new StaticLoginProvider(options.Pin)); if (string.IsNullOrEmpty(options.CertThumbprint)) { List <PKCertificateWithKey> certificates; Console.WriteLine(); Console.WriteLine("Listing Certificates..."); if (string.IsNullOrEmpty(options.Pin)) { certificates = WindowsCertificateStore.LoadPersonalCurrentUser().GetCertificatesWithKey(); } else { certificates = store.GetCertificatesWithKey(); } for (var i = 0; i < certificates.Count; i++) { Console.WriteLine($"[{i}] {certificates[i].Certificate.SubjectDisplayName} (Issued by {certificates[i].Certificate.IssuerDisplayName})"); } Console.WriteLine(); Console.Write("Select the signer certificate: "); var indexstring = Console.ReadLine(); if (!int.TryParse(indexstring, out var index)) { Console.WriteLine($"Error! Invalid index: {indexstring}"); return; } cert = certificates[index]; } else { var thumbprint = PkiUtil.DecodeHexString(options.CertThumbprint); if (string.IsNullOrEmpty(options.Pin)) { cert = WindowsCertificateStore.LoadPersonalCurrentUser().GetCertificatesWithKey().FirstOrDefault(c => c.Certificate.ThumbprintSHA1.SequenceEqual(thumbprint)); } else { cert = store.GetCertificatesWithKey().FirstOrDefault(c => c.Certificate.ThumbprintSHA1.SequenceEqual(thumbprint)); } if (cert == null) { Console.WriteLine($"Error! No certificate was found with thumbprint: {options.CertThumbprint}"); return; } } Console.WriteLine($"Signer: {cert.Certificate.SubjectDisplayName} (thumbprint: {Util.ToHex(cert.Certificate.ThumbprintSHA1)})"); Metadata metadata = null; if (!string.IsNullOrEmpty(options.Metadata) && Util.FileExists(options.Metadata)) { try { var metadataContent = File.ReadAllBytes(options.Metadata); var metadataJson = Encoding.UTF8.GetString(metadataContent); metadata = JsonConvert.DeserializeObject <MetadataModel>(metadataJson).ToEntity(); } catch (Exception ex) { Log(ex.ToString()); Console.WriteLine($"Error parsing metadata file: {ex}"); } } if (string.IsNullOrWhiteSpace(options.File)) { Console.WriteLine("Getting things ready."); Sign(cert, documentsInputDir, signedDocumentsOutputDir, options.Reprocess, options.VisualRep, metadata); } else { var visual = CreateVisualRepresentation(cert.Certificate, options.VisualRep, (metadata != null)); var policy = GetSignaturePolicy().GetPolicy(cert.Certificate); policy.SignerSpecs.AttributeGeneration.EnableLtv = false; if (!SignFile(options.File, cert, policy, visual, metadata, "", "Signed_" + options.File)) { Console.WriteLine($"Error signing file"); return; } else { Console.WriteLine($"File successfully signed."); } } store.Dispose(); }
/// <summary> /// Uninstalls a UA application. /// </summary> public static async Task UninstallApplication(InstalledApplication application) { // validate the executable file. string executableFile = Utils.GetAbsoluteFilePath(application.ExecutableFile, true, true, false); // get the default application name from the executable file. FileInfo executableFileInfo = new FileInfo(executableFile); string applicationName = executableFileInfo.Name.Substring(0, executableFileInfo.Name.Length - 4); // choose a default configuration file. if (String.IsNullOrEmpty(application.ConfigurationFile)) { application.ConfigurationFile = Utils.Format( "{0}\\{1}.Config.xml", executableFileInfo.DirectoryName, applicationName); } // validate the configuration file. string configurationFile = Utils.GetAbsoluteFilePath(application.ConfigurationFile, true, false, false); if (configurationFile != null) { // load the current configuration. Opc.Ua.Security.SecuredApplication security = new Opc.Ua.Security.SecurityConfigurationManager().ReadConfiguration(configurationFile); // delete the application certificates. if (application.DeleteCertificatesOnUninstall) { CertificateIdentifier id = Opc.Ua.Security.SecuredApplication.FromCertificateIdentifier(security.ApplicationCertificate); // delete public key from trusted peers certificate store. try { CertificateStoreIdentifier certificateStore = Opc.Ua.Security.SecuredApplication.FromCertificateStoreIdentifier(security.TrustedCertificateStore); using (ICertificateStore store = certificateStore.OpenStore()) { X509Certificate2Collection peerCertificates = await store.FindByThumbprint(id.Thumbprint); if (peerCertificates.Count > 0) { await store.Delete(peerCertificates[0].Thumbprint); } } } catch (Exception e) { Utils.Trace("Could not delete certificate '{0}' from store. Error={1}", id, e.Message); } // delete private key from application certificate store. try { using (ICertificateStore store = id.OpenStore()) { await store.Delete(id.Thumbprint); } } catch (Exception e) { Utils.Trace("Could not delete certificate '{0}' from store. Error={1}", id, e.Message); } // permentently delete any UA defined stores if they are now empty. try { WindowsCertificateStore store = new WindowsCertificateStore(); await store.Open("LocalMachine\\UA Applications"); X509Certificate2Collection collection = await store.Enumerate(); if (collection.Count == 0) { store.PermanentlyDeleteStore(); } } catch (Exception e) { Utils.Trace("Could not delete certificate '{0}' from store. Error={1}", id, e.Message); } } // remove the permissions for the HTTP endpoints used by the application. if (application.BaseAddresses != null && application.BaseAddresses.Count > 0) { List <ApplicationAccessRule> noRules = new List <ApplicationAccessRule>(); for (int ii = 0; ii < application.BaseAddresses.Count; ii++) { Uri url = Utils.ParseUri(application.BaseAddresses[ii]); if (url != null) { try { HttpAccessRule.SetAccessRules(url, noRules, true); Utils.Trace("Removed HTTP access rules for URL: {0}", url); } catch (Exception e) { Utils.Trace("Could not remove HTTP access rules for URL: {0}. Error={1}", url, e.Message); } } } } } }
/// <summary> /// Updates the children of a node. /// </summary> private void FetchChildren(TreeNode parent) { // get rid of existing children. parent.Nodes.Clear(); // check for a valid node. ContainerInfo info = parent.Tag as ContainerInfo; if (info == null) { return; } // the node type is used to determine what children exist. switch (info.Type) { case ContainerInfoType.Root: { ContainerInfo childInfo = new ContainerInfo(ContainerInfoType.TopLevelStore, "Local Machine"); childInfo.StoreType = WindowsStoreType.LocalMachine; AddNode(parent, childInfo); childInfo = new ContainerInfo(ContainerInfoType.TopLevelStore, "Current User"); childInfo.StoreType = WindowsStoreType.CurrentUser; AddNode(parent, childInfo); childInfo = new ContainerInfo(ContainerInfoType.TopLevelStore, "Services"); childInfo.StoreType = WindowsStoreType.Service; AddNode(parent, childInfo); childInfo = new ContainerInfo(ContainerInfoType.TopLevelStore, "Users"); childInfo.StoreType = WindowsStoreType.User; AddNode(parent, childInfo); break; } case ContainerInfoType.TopLevelStore: { if (info.StoreType == WindowsStoreType.Service) { foreach (ServiceController service in ServiceController.GetServices()) { ContainerInfo childInfo = new ContainerInfo(ContainerInfoType.Service, service.DisplayName); childInfo.StoreType = WindowsStoreType.Service; childInfo.Service = service; AddNode(parent, childInfo); } break; } if (info.StoreType == WindowsStoreType.User) { IList <AccountInfo> users = AccountInfo.Query(null); foreach (AccountInfo user in users) { if (user.SidType == AccountSidType.User) { ContainerInfo childInfo = new ContainerInfo(ContainerInfoType.User, user.Name); childInfo.StoreType = WindowsStoreType.User; childInfo.Account = user; AddNode(parent, childInfo); } } break; } foreach (WindowsCertificateStore store in WindowsCertificateStore.EnumerateStores(info.StoreType, null, null)) { ContainerInfo childInfo = new ContainerInfo(ContainerInfoType.Store, store.DisplayName); childInfo.StoreType = info.StoreType; childInfo.CertificateStore = store; AddNode(parent, childInfo); } break; } case ContainerInfoType.Service: { if (info.Service == null) { break; } foreach (WindowsCertificateStore store in WindowsCertificateStore.EnumerateStores(info.StoreType, null, info.Service.ServiceName)) { ContainerInfo childInfo = new ContainerInfo(ContainerInfoType.Store, store.DisplayName); childInfo.StoreType = info.StoreType; childInfo.CertificateStore = store; AddNode(parent, childInfo); } break; } case ContainerInfoType.User: { if (info.Account == null) { break; } foreach (WindowsCertificateStore store in WindowsCertificateStore.EnumerateStores(info.StoreType, null, info.Account.Sid)) { ContainerInfo childInfo = new ContainerInfo(ContainerInfoType.Store, store.DisplayName); childInfo.StoreType = info.StoreType; childInfo.CertificateStore = store; AddNode(parent, childInfo); } break; } } // add a dummy child to show the + sign. foreach (TreeNode child in parent.Nodes) { child.Nodes.Add(new TreeNode()); } }
/// <summary> /// Uninstalls a UA application. /// </summary> public static async Task UninstallApplication(InstalledApplication application) { // validate the executable file. string executableFile = Utils.GetAbsoluteFilePath(application.ExecutableFile, true, true, false); // get the default application name from the executable file. FileInfo executableFileInfo = new FileInfo(executableFile); string applicationName = executableFileInfo.Name.Substring(0, executableFileInfo.Name.Length-4); // choose a default configuration file. if (String.IsNullOrEmpty(application.ConfigurationFile)) { application.ConfigurationFile = Utils.Format( "{0}\\{1}.Config.xml", executableFileInfo.DirectoryName, applicationName); } // validate the configuration file. string configurationFile = Utils.GetAbsoluteFilePath(application.ConfigurationFile, true, false, false); if (configurationFile != null) { // load the current configuration. Opc.Ua.Security.SecuredApplication security = new Opc.Ua.Security.SecurityConfigurationManager().ReadConfiguration(configurationFile); // delete the application certificates. if (application.DeleteCertificatesOnUninstall) { CertificateIdentifier id = Opc.Ua.Security.SecuredApplication.FromCertificateIdentifier(security.ApplicationCertificate); // delete public key from trusted peers certificate store. try { CertificateStoreIdentifier certificateStore = Opc.Ua.Security.SecuredApplication.FromCertificateStoreIdentifier(security.TrustedCertificateStore); using (ICertificateStore store = certificateStore.OpenStore()) { X509Certificate2Collection peerCertificates = await store.FindByThumbprint(id.Thumbprint); if (peerCertificates.Count > 0) { await store.Delete(peerCertificates[0].Thumbprint); } } } catch (Exception e) { Utils.Trace("Could not delete certificate '{0}' from store. Error={1}", id, e.Message); } // delete private key from application certificate store. try { using (ICertificateStore store = id.OpenStore()) { await store.Delete(id.Thumbprint); } } catch (Exception e) { Utils.Trace("Could not delete certificate '{0}' from store. Error={1}", id, e.Message); } // permentently delete any UA defined stores if they are now empty. try { WindowsCertificateStore store = new WindowsCertificateStore(); await store.Open("LocalMachine\\UA Applications"); X509Certificate2Collection collection = await store.Enumerate(); if (collection.Count == 0) { store.PermanentlyDeleteStore(); } } catch (Exception e) { Utils.Trace("Could not delete certificate '{0}' from store. Error={1}", id, e.Message); } } } }
public void WindowsCertificateStore_GetCertificate_ArgumentThumbprintIsStringEmpty_ExpectedArgumentException() { var store = new WindowsCertificateStore(StoreName.My, StoreLocation.LocalMachine); store.GetCertificate(string.Empty); }
/// <summary> /// Uninstalls a UA application. /// </summary> public static void UninstallApplication(InstalledApplication application) { // validate the executable file. string executableFile = Utils.GetAbsoluteFilePath(application.ExecutableFile, true, true, false); // get the default application name from the executable file. FileInfo executableFileInfo = new FileInfo(executableFile); string applicationName = executableFileInfo.Name.Substring(0, executableFileInfo.Name.Length-4); // choose a default configuration file. if (String.IsNullOrEmpty(application.ConfigurationFile)) { application.ConfigurationFile = Utils.Format( "{0}\\{1}.Config.xml", executableFileInfo.DirectoryName, applicationName); } // install as a service. if (application.InstallAsService) { ServiceInstaller.UnInstallService(application.ApplicationName); } // validate the configuration file. string configurationFile = Utils.GetAbsoluteFilePath(application.ConfigurationFile, true, false, false); if (configurationFile != null) { // load the current configuration. Opc.Ua.Security.SecuredApplication security = new Opc.Ua.Security.SecurityConfigurationManager().ReadConfiguration(configurationFile); // delete the application certificates. if (application.DeleteCertificatesOnUninstall) { CertificateIdentifier id = Opc.Ua.Security.SecuredApplication.FromCertificateIdentifier(security.ApplicationCertificate); // delete public key from trusted peers certificate store. try { CertificateStoreIdentifier certificateStore = Opc.Ua.Security.SecuredApplication.FromCertificateStoreIdentifier(security.TrustedCertificateStore); using (ICertificateStore store = certificateStore.OpenStore()) { X509Certificate2 peerCertificate = store.FindByThumbprint(id.Thumbprint); if (peerCertificate != null) { store.Delete(peerCertificate.Thumbprint); } } } catch (Exception e) { Utils.Trace("Could not delete certificate '{0}' from store. Error={1}", id, e.Message); } // delete private key from application certificate store. try { using (ICertificateStore store = id.OpenStore()) { store.Delete(id.Thumbprint); } } catch (Exception e) { Utils.Trace("Could not delete certificate '{0}' from store. Error={1}", id, e.Message); } // permentently delete any UA defined stores if they are now empty. try { WindowsCertificateStore store = new WindowsCertificateStore(); store.Open("LocalMachine\\UA Applications"); if (store.Enumerate().Count == 0) { store.PermanentlyDeleteStore(); } } catch (Exception e) { Utils.Trace("Could not delete certificate '{0}' from store. Error={1}", id, e.Message); } } // configure firewall. if (application.ConfigureFirewall) { if (security.BaseAddresses != null && security.BaseAddresses.Count > 0) { try { RemoveFirewallAccess(security, executableFile); } catch (Exception e) { Utils.Trace("Could not remove firewall access for executable: {0}. Error={1}", executableFile, e.Message); } } } // remove the permissions for the HTTP endpoints used by the application. if (application.BaseAddresses != null && application.BaseAddresses.Count > 0) { List<ApplicationAccessRule> noRules = new List<ApplicationAccessRule>(); for (int ii = 0; ii < application.BaseAddresses.Count; ii++) { Uri url = Utils.ParseUri(application.BaseAddresses[ii]); if (url != null) { if (url.Scheme == Uri.UriSchemeHttp || url.Scheme == Uri.UriSchemeHttps) { try { HttpAccessRule.SetAccessRules(url, noRules, true); Utils.Trace("Removed HTTP access rules for URL: {0}", url); } catch (Exception e) { Utils.Trace("Could not remove HTTP access rules for URL: {0}. Error={1}", url, e.Message); } } } } } } }