/// <summary> /// set a new application instance certificate /// </summary> /// <param name="newCertificate"></param> private async Task SetOwnCertificateAsync(X509Certificate2 newCertificate) { if (newCertificate == null || !newCertificate.HasPrivateKey) { throw new ArgumentException("Empty or invalid certificate"); } // attempt to replace the old certificate from the various trust lists var oldCertificate = _opcApplicationConfig.SecurityConfiguration .ApplicationCertificate.Certificate; if (oldCertificate?.Thumbprint != newCertificate.Thumbprint) { return; } _logger.Information( "Setting new application certificate {Thumbprint}, {Subject}...", newCertificate.Thumbprint, newCertificate.SubjectName.Name); // copy the certificate, public key only into the trusted certificates list using (var publicKey = new X509Certificate2(newCertificate.RawData)) { var trustList = _opcApplicationConfig.SecurityConfiguration.TrustedPeerCertificates; if (oldCertificate != null) { trustList.Remove(oldCertificate.YieldReturn()); } trustList.Add(newCertificate.YieldReturn()); } // add the certificate to the own store try { var applicationCertificate = _opcApplicationConfig.SecurityConfiguration .ApplicationCertificate; _logger.Information( "Adding own certificate to configured certificate store"); // Remove old and add new if (oldCertificate != null) { applicationCertificate.RemoveFromStore(oldCertificate); } applicationCertificate.AddToStore(newCertificate, true); } catch (Exception ex) { _logger.Warning(ex, "Failed adding own certificate into configured certificate store."); } // // Work around windows issue and persist application certificate also on // directory if configured. This is needed for container persistence. // if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && _configuration.AppCertStoreType == CertificateStoreType.Directory) { var applicationCertificate = new CertificateIdentifier { StoreType = CertificateStoreType.Directory, StorePath = _configuration.OwnCertPath, SubjectName = newCertificate.SubjectName.Name }; try { _logger.Information( "Persisting own certificate into directory certificate store..."); // Remove old and add new if (oldCertificate != null) { applicationCertificate.RemoveFromStore(oldCertificate); } applicationCertificate.AddToStore(newCertificate, true); } catch (Exception ex) { _logger.Warning(ex, "Failed adding own certificate to directory certificate store."); } } _opcApplicationConfig.SecurityConfiguration.ApplicationCertificate .Certificate = newCertificate; await _opcApplicationConfig.CertificateValidator.UpdateCertificate( _opcApplicationConfig.SecurityConfiguration); }