private async void DeleteMI_Click(object sender, EventArgs e) { try { if (ItemsLV.SelectedItems.Count < 1) { return; } DialogResult result = MessageBox.Show( "Are you sure you wish to delete the certificates from the store?", "Delete Certificate", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation); if (result != DialogResult.Yes) { return; } // remove the certificates. List <ListViewItem> itemsToDelete = new List <ListViewItem>(); bool yesToAll = false; using (ICertificateStore store = m_storeId.OpenStore()) { for (int ii = 0; ii < ItemsLV.SelectedItems.Count; ii++) { X509Certificate2 certificate = ItemsLV.SelectedItems[ii].Tag as X509Certificate2; // check for private key. X509Certificate2Collection certificate2 = await store.FindByThumbprint(certificate.Thumbprint); if (!yesToAll && (certificate2.Count > 0) && certificate2[0].HasPrivateKey) { StringBuilder buffer = new StringBuilder(); buffer.Append("Certificate '"); buffer.Append(certificate2[0].Subject); buffer.Append("'"); buffer.Append("Deleting it may cause applications to stop working."); buffer.Append("\r\n"); buffer.Append("\r\n"); buffer.Append("Are you sure you wish to continue?."); DialogResult yesno = new YesNoDlg().ShowDialog(buffer.ToString(), "Delete Private Key", true); if (yesno == DialogResult.No) { continue; } yesToAll = yesno == DialogResult.Retry; } if (certificate != null) { await store.Delete(certificate.Thumbprint); itemsToDelete.Add(ItemsLV.SelectedItems[ii]); } } } // remove the items. foreach (ListViewItem itemToDelete in itemsToDelete) { itemToDelete.Remove(); } } catch (Exception exception) { GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); await Initialize(m_storeId, m_thumbprints); } }
/// <summary> /// Displays the applications in the control. /// </summary> internal async Task Initialize(CertificateStoreIdentifier id, IList <string> thumbprints) { ItemsLV.Items.Clear(); m_storeId = id; m_thumbprints = thumbprints; if (m_storeId == null || String.IsNullOrEmpty(m_storeId.StoreType) || String.IsNullOrEmpty(m_storeId.StorePath)) { Instructions = "No certificates are in the store."; AdjustColumns(); return; } try { // get the store. using (ICertificateStore store = m_storeId.OpenStore()) { // only show certificates with the specified thumbprint. if (thumbprints != null) { Instructions = "None of the selected certificates can be found in the store."; foreach (string thumbprint in thumbprints) { X509Certificate2Collection certificates = await store.FindByThumbprint(thumbprint); if (certificates.Count > 0) { AddItem(certificates[0]); } } } // show all certificates. else { Instructions = "No certificates are in the store."; X509Certificate2Collection certificates = await store.Enumerate(); foreach (X509Certificate2 certificate in certificates) { AddItem(certificate); } } } } catch (Exception e) { Instructions = "An error occurred opening the store: " + e.Message; } // save the unfiltered list. m_items = new List <ListViewItem>(ItemsLV.Items.Count); foreach (ListViewItem item in ItemsLV.Items) { m_items.Add(item); } AdjustColumns(); }
/// <summary> /// Synchronous helper implementation of CheckApplicationInstanceCertificate for C++ Proxy /// </summary> public static void CheckApplicationInstanceCertificate(ApplicationConfiguration configuration) { // create a default certificate id none specified. CertificateIdentifier id = configuration.SecurityConfiguration.ApplicationCertificate; if (id == null) { id = new CertificateIdentifier(); id.StoreType = Utils.DefaultStoreType; id.StorePath = Utils.DefaultStorePath; id.SubjectName = configuration.ApplicationName; } // check for certificate with a private key. X509Certificate2 certificate = null; Task.Run(async() => certificate = await id.Find(true)).Wait(); if (certificate != null) { return; } // construct the subject name from the List <string> hostNames = new List <string>(); hostNames.Add(Utils.GetHostName()); string commonName = Utils.Format("CN={0}", configuration.ApplicationName); string domainName = Utils.Format("DC={0}", hostNames[0]); string subjectName = Utils.Format("{0}, {1}", commonName, domainName); // create a new certificate with a new public key pair. certificate = CertificateFactory.CreateCertificate( id.StoreType, id.StorePath, configuration.ApplicationUri, configuration.ApplicationName, subjectName, hostNames, 2048, 120, 256); // update and save the configuration file. id.Certificate = certificate; configuration.SaveToFile(configuration.SourceFilePath); // add certificate to the trusted peer store so other applications will trust it. ICertificateStore store = configuration.SecurityConfiguration.TrustedPeerCertificates.OpenStore(); try { Task.Run(async() => { X509Certificate2Collection certificateCollection = await store.FindByThumbprint(certificate.Thumbprint); if (certificateCollection != null) { await store.Add(certificateCollection[0]); } } ).Wait(); } finally { store.Close(); } // tell the certificate validator about the new certificate. configuration.CertificateValidator.Update(configuration.SecurityConfiguration); }
/// <summary> /// Adds the certificate to the Trusted Certificate Store /// </summary> /// <param name="configuration">The application's configuration which specifies the location of the TrustedStore.</param> /// <param name="certificate">The certificate to register.</param> private static async Task AddToTrustedStore(ApplicationConfiguration configuration, X509Certificate2 certificate) { if (certificate == null) { throw new ArgumentNullException(nameof(certificate)); } string storePath = null; if (configuration != null && configuration.SecurityConfiguration != null && configuration.SecurityConfiguration.TrustedPeerCertificates != null) { storePath = configuration.SecurityConfiguration.TrustedPeerCertificates.StorePath; } if (String.IsNullOrEmpty(storePath)) { Utils.Trace(Utils.TraceMasks.Information, "WARNING: Trusted peer store not specified."); return; } try { ICertificateStore store = configuration.SecurityConfiguration.TrustedPeerCertificates.OpenStore(); if (store == null) { Utils.Trace("Could not open trusted peer store. StorePath={0}", storePath); return; } try { // check if it already exists. X509Certificate2Collection existingCertificates = await store.FindByThumbprint(certificate.Thumbprint).ConfigureAwait(false); if (existingCertificates.Count > 0) { return; } Utils.Trace(Utils.TraceMasks.Information, "Adding certificate to trusted peer store. StorePath={0}", storePath); List <string> subjectName = X509Utils.ParseDistinguishedName(certificate.Subject); // check for old certificate. X509Certificate2Collection certificates = await store.Enumerate().ConfigureAwait(false); for (int ii = 0; ii < certificates.Count; ii++) { if (X509Utils.CompareDistinguishedName(certificates[ii], subjectName)) { if (certificates[ii].Thumbprint == certificate.Thumbprint) { return; } await store.Delete(certificates[ii].Thumbprint).ConfigureAwait(false); break; } } // add new certificate. X509Certificate2 publicKey = new X509Certificate2(certificate.RawData); await store.Add(publicKey).ConfigureAwait(false); } finally { store.Close(); } } catch (Exception e) { Utils.Trace(e, "Could not add certificate to trusted peer store. StorePath={0}", storePath); } }
private async void CertificateRequestTimer_Tick(object sender, EventArgs e) { try { NodeId requestId = NodeId.Parse(m_application.CertificateRequestId); byte[] privateKey = null; byte[][] issuerCertificates = null; byte[] certificate = m_gds.FinishRequest( m_application.ApplicationId, requestId, out privateKey, out issuerCertificates); if (certificate == null) { return; } CertificateRequestTimer.Enabled = false; RequestProgressLabel.Visible = false; if (m_application.RegistrationType != RegistrationType.ServerPush) { // save public key. if (!String.IsNullOrEmpty(m_application.CertificatePublicKeyPath)) { string file = Utils.GetAbsoluteFilePath(m_application.CertificatePublicKeyPath, true, false, true); File.WriteAllBytes(file, certificate); } // check if the private was re-used. if (privateKey == null || privateKey.Length == 0) { if (!String.IsNullOrEmpty(m_application.CertificatePrivateKeyPath)) { string path = Utils.GetAbsoluteFilePath(m_application.CertificatePrivateKeyPath, true, true, true); if (path != null) { if (!m_application.CertificatePrivateKeyPath.EndsWith("PEM", StringComparison.OrdinalIgnoreCase)) { var x509 = new X509Certificate2(certificate); var oldPfx = new X509Certificate2(path, (string)null, X509KeyStorageFlags.Exportable); var newPfx = CertificateAuthority.Replace(x509, oldPfx); var bytes = newPfx.Export(X509ContentType.Pfx); File.WriteAllBytes(path, bytes); } } } else { if (!String.IsNullOrEmpty(m_application.CertificateStorePath) && !String.IsNullOrEmpty(m_application.CertificateSubjectName)) { var x509 = new X509Certificate2(certificate); var cid = new CertificateIdentifier() { StorePath = m_application.CertificateStorePath, SubjectName = m_application.CertificateSubjectName.Replace("localhost", System.Net.Dns.GetHostName()) }; var oldPfx = await cid.Find(true); if (oldPfx != null) { var newPfx = CertificateAuthority.Replace(x509, oldPfx); using (var store = CertificateStoreIdentifier.OpenStore(m_application.CertificateStorePath)) { await store.Delete(oldPfx.Thumbprint); await store.Add(newPfx); } } } } } // save private key. else { if (!String.IsNullOrEmpty(m_application.CertificatePrivateKeyPath)) { string path = Utils.GetAbsoluteFilePath(m_application.CertificatePrivateKeyPath, true, true, true); if (path != null) { File.WriteAllBytes(path, privateKey); } } else { if (!String.IsNullOrEmpty(m_application.CertificateStorePath) && !String.IsNullOrEmpty(m_application.CertificateSubjectName)) { var cid = new CertificateIdentifier() { StorePath = m_application.CertificateStorePath, SubjectName = m_application.CertificateSubjectName }; var oldCertificate = await cid.Find(); using (var store = CertificateStoreIdentifier.OpenStore(m_application.CertificateStorePath)) { if (oldCertificate != null) { await store.Delete(oldCertificate.Thumbprint); } var x509 = new X509Certificate2(privateKey, new System.Security.SecureString(), X509KeyStorageFlags.Exportable); x509 = CertificateFactory.Load(x509, true); await store.Add(x509); } } } } // update trust list. if (!String.IsNullOrEmpty(m_application.TrustListStorePath)) { using (ICertificateStore store = CertificateStoreIdentifier.OpenStore(m_application.TrustListStorePath)) { foreach (var issuerCertificate in issuerCertificates) { var x509 = new X509Certificate2(issuerCertificate); if (store.FindByThumbprint(x509.Thumbprint) == null) { await store.Add(new X509Certificate2(issuerCertificate)); } } } } } else { if (privateKey != null && privateKey.Length > 0) { var x509 = new X509Certificate2(privateKey, m_certificatePassword, X509KeyStorageFlags.Exportable); privateKey = x509.Export(X509ContentType.Pfx); } bool applyChanges = m_server.UpdateCertificate(null, null, certificate, GetPrivateKeyFormat(), privateKey, issuerCertificates); if (applyChanges) { MessageBox.Show( Parent, "The certificate was updated, however, the apply changes command must be sent before the server will use the new certificate.", Parent.Text, MessageBoxButtons.OK, MessageBoxIcon.Information); ApplyChangesButton.Enabled = true; } } m_certificate = new X509Certificate2(certificate); CertificateControl.ShowValue(null, "Application Certificate", new CertificateWrapper() { Certificate = m_certificate }, true); } catch (Exception exception) { var sre = exception as ServiceResultException; if (sre != null && sre.StatusCode == StatusCodes.BadNothingToDo) { return; } MessageBox.Show(Parent.Text + ": " + exception.Message); CertificateRequestTimer.Enabled = false; } }
private ServiceResult RemoveCertificate( ISystemContext context, MethodState method, NodeId objectId, string thumbprint, bool isTrustedCertificate) { HasSecureWriteAccess(context); lock (m_lock) { if (m_sessionId != null) { return(StatusCodes.BadInvalidState); } if (String.IsNullOrEmpty(thumbprint)) { return(StatusCodes.BadInvalidArgument); } using (ICertificateStore store = CertificateStoreIdentifier.OpenStore(isTrustedCertificate ? m_trustedStorePath : m_issuerStorePath)) { var certCollection = store.FindByThumbprint(thumbprint).Result; if (certCollection.Count == 0) { return(StatusCodes.BadInvalidArgument); } // delete all CRLs signed by cert var crlsToDelete = new List <X509CRL>(); foreach (var crl in store.EnumerateCRLs()) { foreach (var cert in certCollection) { if (Utils.CompareDistinguishedName(cert.Subject, crl.Issuer) && crl.VerifySignature(cert, false)) { crlsToDelete.Add(crl); break; } } } if (!store.Delete(thumbprint).Result) { return(StatusCodes.BadInvalidArgument); } foreach (var crl in crlsToDelete) { if (!store.DeleteCRL(crl)) { // intentionally ignore errors, try best effort Utils.Trace("RemoveCertificate: Failed to delete CRL {0}.", crl.ToString()); } } } m_node.LastUpdateTime.Value = DateTime.UtcNow; } return(ServiceResult.Good); }
private ServiceResult RemoveCertificate( ISystemContext context, MethodState method, NodeId objectId, string thumbprint, bool isTrustedCertificate) { HasSecureWriteAccess(context); ServiceResult result = StatusCodes.Good; lock (m_lock) { if (m_sessionId != null) { result = StatusCodes.BadInvalidState; } else if (String.IsNullOrEmpty(thumbprint)) { result = StatusCodes.BadInvalidArgument; } else { using (ICertificateStore store = CertificateStoreIdentifier.OpenStore(isTrustedCertificate ? m_trustedStorePath : m_issuerStorePath)) { var certCollection = store.FindByThumbprint(thumbprint).GetAwaiter().GetResult(); if (certCollection.Count == 0) { result = StatusCodes.BadInvalidArgument; } else { // delete all CRLs signed by cert var crlsToDelete = new X509CRLCollection(); foreach (var crl in store.EnumerateCRLs().GetAwaiter().GetResult()) { foreach (var cert in certCollection) { if (X509Utils.CompareDistinguishedName(cert.SubjectName, crl.IssuerName) && crl.VerifySignature(cert, false)) { crlsToDelete.Add(crl); break; } } } if (!store.Delete(thumbprint).GetAwaiter().GetResult()) { result = StatusCodes.BadInvalidArgument; } else { foreach (var crl in crlsToDelete) { if (!store.DeleteCRL(crl).GetAwaiter().GetResult()) { // intentionally ignore errors, try best effort Utils.LogError("RemoveCertificate: Failed to delete CRL {0}.", crl.ToString()); } } } } } m_node.LastUpdateTime.Value = DateTime.UtcNow; } } // report the TrustListUpdatedAuditEvent object[] inputParameters = new object[] { thumbprint }; m_node.ReportTrustListUpdatedAuditEvent(context, objectId, "Method/RemoveCertificate", method.NodeId, inputParameters, result.StatusCode); return(result); }
public override async Task Init() { Utils.Trace(Utils.TraceMasks.Information, "InitializeCertificateGroup: {0}", m_subjectName); X509Certificate2Collection rootCACertificateChain; IList <Opc.Ua.X509CRL> rootCACrlChain; try { // read root CA chain for certificate group rootCACertificateChain = await _opcVaultHandler.GetCACertificateChainAsync(Configuration.Id).ConfigureAwait(false); rootCACrlChain = await _opcVaultHandler.GetCACrlChainAsync(Configuration.Id).ConfigureAwait(false); var rootCaCert = rootCACertificateChain[0]; var rootCaCrl = rootCACrlChain[0]; if (Utils.CompareDistinguishedName(rootCaCert.Subject, m_subjectName)) { Certificate = rootCaCert; rootCaCrl.VerifySignature(rootCaCert, true); } else { throw new ServiceResultException("Key Vault certificate subject(" + rootCaCert.Subject + ") does not match cert group subject " + m_subjectName); } } catch (Exception ex) { Utils.Trace("Failed to load CA certificate " + Configuration.Id + " from key Vault "); Utils.Trace(ex.Message); throw ex; } // add all existing cert versions to trust list // erase old certs using (ICertificateStore store = CertificateStoreIdentifier.OpenStore(m_authoritiesStorePath)) { try { X509Certificate2Collection certificates = await store.Enumerate(); foreach (var certificate in certificates) { // TODO: Subject may have changed over time if (Utils.CompareDistinguishedName(certificate.Subject, m_subjectName)) { var certs = rootCACertificateChain.Find(X509FindType.FindByThumbprint, certificate.Thumbprint, false); if (certs == null || certs.Count == 0) { Utils.Trace("Delete CA certificate from authority store: " + certificate.Thumbprint); // delete existing CRL in trusted list foreach (var crl in store.EnumerateCRLs(certificate, false)) { if (crl.VerifySignature(certificate, false)) { store.DeleteCRL(crl); } } await store.Delete(certificate.Thumbprint); } } } } catch (Exception ex) { Utils.Trace("Failed to Delete existing certificates from authority store: " + ex.Message); } foreach (var rootCACertificate in rootCACertificateChain) { X509Certificate2Collection certs = await store.FindByThumbprint(rootCACertificate.Thumbprint); if (certs.Count == 0) { await store.Add(rootCACertificate); Utils.Trace("Added CA certificate to authority store: " + rootCACertificate.Thumbprint); } else { Utils.Trace("CA certificate already exists in authority store: " + rootCACertificate.Thumbprint); } foreach (var rootCACrl in rootCACrlChain) { if (rootCACrl.VerifySignature(rootCACertificate, false)) { // delete existing CRL in trusted list foreach (var crl in store.EnumerateCRLs(rootCACertificate, false)) { if (crl.VerifySignature(rootCACertificate, false)) { store.DeleteCRL(crl); } } store.AddCRL(rootCACrl); } } } // load trust list from server var trustList = await _opcVaultHandler.GetTrustListAsync(Configuration.Id).ConfigureAwait(false); await UpdateTrustList(trustList); } }
/// <summary> /// Creates an application instance certificate if one does not already exist. /// </summary> public static void CheckApplicationInstanceCertificate(ApplicationConfiguration configuration) { // create a default certificate id none specified. CertificateIdentifier id = configuration.SecurityConfiguration.ApplicationCertificate; if (id == null) { id = new CertificateIdentifier(); id.StoreType = CertificateStoreType.Windows; id.StorePath = "LocalMachine\\My"; id.SubjectName = configuration.ApplicationName; } // check for certificate with a private key. X509Certificate2 certificate = id.Find(true); if (certificate != null) { //This UA application already has an instance certificate SaveCertificate(certificate); return; } //This UA application does not have an instance certificate. Create one automatically // construct the subject name from the List <string> hostNames = new List <string>(); hostNames.Add(System.Net.Dns.GetHostName()); string commonName = Utils.Format("CN={0}", configuration.ApplicationName); string domainName = Utils.Format("DC={0}", hostNames[0]); string subjectName = Utils.Format("{0}, {1}", commonName, domainName); // check if a distinguished name was specified. if (id.SubjectName.IndexOf("=", StringComparison.Ordinal) != -1) { List <string> fields = Utils.ParseDistinguishedName(id.SubjectName); bool commonNameFound = false; bool domainNameFound = false; for (int ii = 0; ii < fields.Count; ii++) { string field = fields[ii]; if (field.StartsWith("CN=")) { fields[ii] = commonName; commonNameFound = true; continue; } if (field.StartsWith("DC=")) { fields[ii] = domainName; domainNameFound = true; continue; } } if (!commonNameFound) { fields.Insert(0, commonName); } if (!domainNameFound) { fields.Insert(0, domainName); } StringBuilder buffer = new StringBuilder(); for (int ii = 0; ii < fields.Count; ii++) { if (buffer.Length > 0) { buffer.Append(", "); } buffer.Append(fields[ii]); } subjectName = buffer.ToString(); } // create a new certificate with a new public key pair. certificate = CertificateFactory.CreateCertificate( id.StoreType, id.StorePath, configuration.ApplicationUri, configuration.ApplicationName, subjectName, hostNames, 1024, 120); // update and save the configuration file. id.Certificate = certificate; configuration.SaveToFile(configuration.SourceFilePath); // add certificate to the trusted peer store so other applications will trust it. ICertificateStore store = configuration.SecurityConfiguration.TrustedPeerCertificates.OpenStore(); try { X509Certificate2 certificate2 = store.FindByThumbprint(certificate.Thumbprint); if (certificate2 == null) { store.Add(certificate); } } finally { store.Close(); } // tell the certificate validator about the new certificate. configuration.CertificateValidator.Update(configuration.SecurityConfiguration); SaveCertificate(certificate); }
private void PullFromGds(bool deleteBeforeAdd) { try { NodeId trustListId = m_gds.GetTrustList(m_application.ApplicationId, null); if (trustListId == null) { CertificateStoreControl.Initialize(null, null, null); return; } var trustList = m_gds.ReadTrustList(trustListId); if (m_application.RegistrationType == RegistrationType.ServerPush) { CertificateStoreControl.Initialize(trustList); MessageBox.Show( Parent, "The trust list (include CRLs) was downloaded from the GDS. It now has to be pushed to the Server.", Parent.Text, MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (!String.IsNullOrEmpty(m_trustListStorePath)) { if (deleteBeforeAdd) { DeleteExistingFromStore(m_trustListStorePath).Wait(); DeleteExistingFromStore(m_issuerListStorePath).Wait();; } } if (!String.IsNullOrEmpty(m_trustListStorePath)) { using (ICertificateStore store = CertificateStoreIdentifier.OpenStore(m_trustListStorePath)) { if ((trustList.SpecifiedLists & (uint)Opc.Ua.TrustListMasks.TrustedCertificates) != 0) { foreach (var certificate in trustList.TrustedCertificates) { var x509 = new X509Certificate2(certificate); X509Certificate2Collection certs = store.FindByThumbprint(x509.Thumbprint).Result; if (certs.Count == 0) { store.Add(x509).Wait(); } } } if ((trustList.SpecifiedLists & (uint)Opc.Ua.TrustListMasks.TrustedCrls) != 0) { foreach (var crl in trustList.TrustedCrls) { store.AddCRL(new X509CRL(crl)); } } } } if (!String.IsNullOrEmpty(m_application.IssuerListStorePath)) { using (ICertificateStore store = CertificateStoreIdentifier.OpenStore(m_application.IssuerListStorePath)) { if ((trustList.SpecifiedLists & (uint)Opc.Ua.TrustListMasks.IssuerCertificates) != 0) { foreach (var certificate in trustList.IssuerCertificates) { var x509 = new X509Certificate2(certificate); X509Certificate2Collection certs = store.FindByThumbprint(x509.Thumbprint).Result; if (certs.Count == 0) { store.Add(x509).Wait(); } } } if ((trustList.SpecifiedLists & (uint)Opc.Ua.TrustListMasks.IssuerCrls) != 0) { foreach (var crl in trustList.IssuerCrls) { store.AddCRL(new X509CRL(crl)); } } } } CertificateStoreControl.Initialize(m_trustListStorePath, m_issuerListStorePath, null); MessageBox.Show( Parent, "The trust list (include CRLs) was downloaded from the GDS and saved locally.", Parent.Text, MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception exception) { MessageBox.Show(Parent.Text + ": " + exception.Message); } }
private void OkBTN_Click(object sender, EventArgs e) { try { string storeType = null; string storePath = null; string domainName = null; string organization = null; string subjectName = SubjectNameTB.Text.Trim(); string issuerKeyFilePath = IssuerKeyFilePathTB.Text.Trim(); string issuerKeyFilePassword = IssuerPasswordTB.Text.Trim(); if (String.IsNullOrEmpty(issuerKeyFilePath)) { throw new ApplicationException("Must provide an issuer certificate."); } // verify certificate. X509Certificate2 issuer = new X509Certificate2( issuerKeyFilePath, issuerKeyFilePassword, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet); if (!issuer.HasPrivateKey) { throw new ApplicationException("Issuer certificate does not have a private key."); } // determine certificate type. foreach (X509Extension extension in issuer.Extensions) { X509BasicConstraintsExtension basicContraints = extension as X509BasicConstraintsExtension; if (basicContraints != null) { if (!basicContraints.CertificateAuthority) { throw new ApplicationException("Certificate cannot be used to issue new certificates."); } } } // check traget store. if (!String.IsNullOrEmpty(CertificateStoreCTRL.StorePath)) { storeType = CertificateStoreCTRL.StoreType; storePath = CertificateStoreCTRL.StorePath; } if (String.IsNullOrEmpty(storePath)) { throw new ApplicationException("Please specify a store path."); } domainName = DomainNameTB.Text; organization = OrganizationTB.Text; // extract key fields from the subject name. if (SubjectNameCK.Checked) { List <string> parts = Utils.ParseDistinguishedName(SubjectNameTB.Text); for (int ii = 0; ii < parts.Count; ii++) { if (parts[ii].StartsWith("CN=")) { domainName = parts[ii].Substring(3).Trim(); } if (parts[ii].StartsWith("O=")) { organization = parts[ii].Substring(2).Trim(); } } } if (String.IsNullOrEmpty(domainName)) { throw new ApplicationException("Please specify a domain name."); } if (!String.IsNullOrEmpty(DomainNameTB.Text) && domainName != DomainNameTB.Text) { throw new ApplicationException("The domain name must be the common name for the certificate."); } if (!String.IsNullOrEmpty(OrganizationTB.Text) && organization != OrganizationTB.Text) { throw new ApplicationException("The organization must be the organization for the certificate."); } X509Certificate2 certificate = Opc.Ua.CertificateFactory.CreateCertificate( storeType, storePath, null, null, domainName, subjectName, null, Convert.ToUInt16(KeySizeCB.SelectedItem.ToString()), DateTime.MinValue, (ushort)LifeTimeInMonthsUD.Value, 0, false, false, issuerKeyFilePath, issuerKeyFilePassword); m_certificate = new CertificateIdentifier(); m_certificate.StoreType = storeType; m_certificate.StorePath = storePath; m_certificate.Certificate = certificate; try { CertificateStoreIdentifier rootStore = new CertificateStoreIdentifier(); rootStore.StoreType = CertificateStoreType.Windows; rootStore.StorePath = "LocalMachine\\Root"; using (ICertificateStore store = rootStore.OpenStore()) { X509Certificate2 rootCertificate = new X509Certificate2(issuerKeyFilePath, issuerKeyFilePassword, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet); if (store.FindByThumbprint(rootCertificate.Thumbprint) == null) { if (Ask("Would you like to install the signing certificate as a trusted root authority on this machine?")) { store.Add(new X509Certificate2(rootCertificate.RawData)); } } } } catch (Exception exception) { GuiUtils.HandleException(this.Text, System.Reflection.MethodBase.GetCurrentMethod(), exception); } // close the dialog. DialogResult = DialogResult.OK; } catch (Exception exception) { GuiUtils.HandleException(this.Text, System.Reflection.MethodBase.GetCurrentMethod(), exception); } }