[Test]         // bug #333699
        public void FromString_EntityReferences()
        {
            const string xml = @"
				<values>
					<value name=""&quot;name&quot;&amp;&lt;address&gt;"">&lt;&apos;Suds&apos; &amp; &quot;Soda&quot;&gt;!</value>
				</values>"                ;

            SecurityElement se = SecurityElement.FromString(xml);

            Assert.IsNotNull(se, "#A1");
            Assert.IsNull(se.Attributes, "#A2");
            Assert.IsNotNull(se.Children, "#A3");
            Assert.AreEqual(1, se.Children.Count, "#A4");
            Assert.AreEqual("values", se.Tag, "#A5");
            Assert.IsNull(se.Text, "#A6");

            SecurityElement child = se.Children [0] as SecurityElement;

            Assert.IsNotNull(child, "#B1");
            Assert.IsNotNull(child.Attributes, "#B2");
            Assert.AreEqual("\"name\"&<address>", child.Attribute("name"), "#B3");
            Assert.AreEqual("value", child.Tag, "#B4");
            Assert.AreEqual("<'Suds' & \"Soda\">!", child.Text, "#B5");
            Assert.IsNull(child.Children, "#B6");
        }
Пример #2
0
 private static IApplicationTrustManager DecodeAppTrustManager()
 {
     if (File.InternalExists(ApplicationSecurityManager.s_machineConfigFile))
     {
         string end;
         using (FileStream fileStream = new FileStream(ApplicationSecurityManager.s_machineConfigFile, FileMode.Open, FileAccess.Read))
             end = new StreamReader((Stream)fileStream).ReadToEnd();
         SecurityElement securityElement1 = SecurityElement.FromString(end).SearchForChildByTag("mscorlib");
         if (securityElement1 != null)
         {
             SecurityElement securityElement2 = securityElement1.SearchForChildByTag("security");
             if (securityElement2 != null)
             {
                 SecurityElement securityElement3 = securityElement2.SearchForChildByTag("policy");
                 if (securityElement3 != null)
                 {
                     SecurityElement securityElement4 = securityElement3.SearchForChildByTag("ApplicationSecurityManager");
                     if (securityElement4 != null)
                     {
                         SecurityElement elTrustManager = securityElement4.SearchForChildByTag("IApplicationTrustManager");
                         if (elTrustManager != null)
                         {
                             IApplicationTrustManager applicationTrustManager = ApplicationSecurityManager.DecodeAppTrustManagerFromElement(elTrustManager);
                             if (applicationTrustManager != null)
                             {
                                 return(applicationTrustManager);
                             }
                         }
                     }
                 }
             }
         }
     }
     return(ApplicationSecurityManager.DecodeAppTrustManagerFromElement(ApplicationSecurityManager.CreateDefaultApplicationTrustManagerElement()));
 }
Пример #3
0
        // In Fx 1.0/1.1 there is not direct way to load a XML file
        // into a SecurityElement so we use SecurityParser from
        // Mono.Security.dll.
        static SecurityElement LoadXml(string filename)
        {
            if (!File.Exists(filename))
            {
                Console.WriteLine("Couldn't not find '{0}'.", filename);
                return(null);
            }

            string xml = null;

            using (StreamReader sr = new StreamReader(filename))
            {
                xml = sr.ReadToEnd();
                sr.Close();
            }
#if NET_2_0
            // actually this use the SecurityParser (on the Mono
            // runtime) in corlib do to the job - but it remove
            // the dependency on Mono.Security.dll
            SecurityElement se = SecurityElement.FromString(xml);
#else
            SecurityParser sp = new SecurityParser();
            sp.LoadXml(xml);
            SecurityElement se = sp.ToXml();
#endif
            return(se);
        }
Пример #4
0
        /// <summary>
        /// return the appdomain with permission set in medium trust level
        /// </summary>
        /// <returns> appdomain</returns>
        private AppDomain GetCustomizedAppDomain()
        {
            AppDomainSetup setup = new AppDomainSetup {
                ApplicationBase = Environment.CurrentDirectory
            };

            setup.AppDomainInitializer = SetupAppDomain;
            var          ps      = new PermissionSet(PermissionState.None);
            StreamReader fs      = new StreamReader("AstoriaClientTest_MediumTrustPermissionSet.xml");
            string       strPerm = fs.ReadToEnd();

            strPerm = strPerm.Replace("$AppDir$", Environment.CurrentDirectory);
            ps.FromXml(SecurityElement.FromString(strPerm));
            AddPermissionByTest(ps);

            StrongName framework  = Assembly.GetExecutingAssembly().Evidence.GetHostEvidence <StrongName>();
            StrongName moduleCore = typeof(TestItem).Assembly.Evidence.GetHostEvidence <StrongName>();
            StrongName kokomo     = typeof(ModelEngineOptions).Assembly.Evidence.GetHostEvidence <StrongName>();

            StrongName[] sn = { framework, moduleCore, kokomo };

            AppDomain myDomain = AppDomain.CreateDomain("myDomain", null, setup, ps, sn);

            return(myDomain);
        }
Пример #5
0
        public static SecurityConfig Load()
        {
            SecurityConfig scfg = new SecurityConfig();

            TextReader tr = null;

            try
            {
                tr = File.OpenText(DefaultConfigFile);
                string        xml = tr.ReadToEnd();
                PermissionSet ps  = new PermissionSet(null);
                ps.FromXml(SecurityElement.FromString(xml));
                scfg._GridThreadPermissions = ps;
            }
            finally
            {
                try
                {
                    if (tr != null)
                    {
                        tr.Close();
                    }
                }
                catch { }
            }
            return(scfg);
        }
Пример #6
0
        public void XmlEqualsTest()
        {
            string xml = @"<root><child1/><child2><child3 attr1=""a"" /></child2><child4>Text</child4></root>";

            SecurityElement original = SecurityElement.FromString(xml);

            // Elements should be equal to themseleves, and to elements made from the same XML
            SecurityElement same = SecurityElement.FromString(xml);

            Assert.IsTrue(original.XmlEquals(original));
            Assert.IsTrue(original.XmlEquals(same));
            Assert.IsTrue(same.XmlEquals(original));

            // Adding attributes should cause a comparison error
            SecurityElement addAttr = SecurityElement.FromString(xml);

            addAttr.AddAttribute("newAttr", "value");
            Assert.IsFalse(original.XmlEquals(addAttr));
            Assert.IsFalse(addAttr.XmlEquals(original));

            // Adding children should cause comparison errors
            SecurityElement addChild = SecurityElement.FromString(xml);

            addChild.AddChild(new SecurityElement("newChild"));
            Assert.IsFalse(original.XmlEquals(addChild));
            Assert.IsFalse(addChild.XmlEquals(original));
        }
Пример #7
0
        private static PermissionSet RemoveNonReferencedPermissions(string[] setToFilter, ITaskItem[] dependencies)
        {
            PermissionSet set = new PermissionSet(PermissionState.None);

            if (((dependencies == null) || (setToFilter == null)) || (setToFilter.Length == 0))
            {
                return(set);
            }
            List <string> list = new List <string>();

            foreach (ITaskItem item in dependencies)
            {
                AssemblyName assemblyName = AssemblyName.GetAssemblyName(item.ItemSpec);
                list.Add(assemblyName.Name + ", " + assemblyName.Version.ToString());
            }
            SecurityElement permissionSetXml = set.ToXml();

            foreach (string str in setToFilter)
            {
                string str2;
                string str3;
                string str4;
                if ((!string.IsNullOrEmpty(str) && ParseElementForAssemblyIdentification(SecurityElement.FromString(str), out str3, out str2, out str4)) && list.Contains(str2 + ", " + str4))
                {
                    permissionSetXml.AddChild(SecurityElement.FromString(str));
                }
            }
            return(new ReadOnlyPermissionSet(permissionSetXml));
        }
        private static IApplicationTrustManager DecodeAppTrustManager()
        {
            if (!File.InternalExists(s_machineConfigFile))
            {
                goto defaultTrustManager;
            }

            // A config file exists. Decode the trust manager from its Xml.
            String configFileStr;

            using (FileStream contents = new FileStream(s_machineConfigFile, FileMode.Open, FileAccess.Read))
            {
                configFileStr = new StreamReader(contents).ReadToEnd();
            }

            SecurityElement elRoot     = SecurityElement.FromString(configFileStr);
            SecurityElement elMscorlib = elRoot.SearchForChildByTag("mscorlib");

            if (elMscorlib == null)
            {
                goto defaultTrustManager;
            }
            SecurityElement elSecurity = elMscorlib.SearchForChildByTag("security");

            if (elSecurity == null)
            {
                goto defaultTrustManager;
            }
            SecurityElement elPolicy = elSecurity.SearchForChildByTag("policy");

            if (elPolicy == null)
            {
                goto defaultTrustManager;
            }
            SecurityElement elSecurityManager = elPolicy.SearchForChildByTag("ApplicationSecurityManager");

            if (elSecurityManager == null)
            {
                goto defaultTrustManager;
            }
            SecurityElement elTrustManager = elSecurityManager.SearchForChildByTag("IApplicationTrustManager");

            if (elTrustManager == null)
            {
                goto defaultTrustManager;
            }
            IApplicationTrustManager appTrustManager = DecodeAppTrustManagerFromElement(elTrustManager);

            if (appTrustManager == null)
            {
                goto defaultTrustManager;
            }
            return(appTrustManager);

defaultTrustManager:
            return(DecodeAppTrustManagerFromElement(CreateDefaultApplicationTrustManagerElement()));
        }
        public void Copy()
        {
            SecurityElement se   = SecurityElement.FromString("<tag attribute=\"value\"><child attr=\"1\">mono</child><child/></tag>");
            SecurityElement copy = se.Copy();

            Assert.IsFalse(Object.ReferenceEquals(se, copy), "se!ReferenceEquals");
            Assert.IsTrue(Object.ReferenceEquals(se.Children [0], copy.Children [0]), "c1=ReferenceEquals");
            Assert.IsTrue(Object.ReferenceEquals(se.Children [1], copy.Children [1]), "c2=ReferenceEquals");
        }
Пример #10
0
        public static PluginHost Create(string pluginId, IDictionary <string, object> config)
        {
            var currentDirectory = Directory.GetCurrentDirectory();

            var setup = new AppDomainSetup
            {
                ApplicationBase          = currentDirectory,
                ApplicationName          = pluginId,
                ConfigurationFile        = "", // DO not set to empty string if we want to use the conf file from this domain
                DisallowBindingRedirects = true,
                DisallowCodeDownload     = true,
                DisallowPublisherPolicy  = true
            };

            var permissions = new PermissionSet(PermissionState.None);

            if (config.ContainsKey("Permissions") && config["Permissions"] != null)
            {
                var securityElement = SecurityElement.FromString(config["Permissions"].ToString());

                if (securityElement != null)
                {
                    permissions.FromXml(securityElement);
                }
            }

            permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.ControlEvidence // To get nice exceptions with permission demands.
                                                             | SecurityPermissionFlag.ControlPolicy // See ^
                                                             | SecurityPermissionFlag.Execution     // To allow the plugin to execute
                                                             ));


            // WCF hosting for JSONRPC
            permissions.AddPermission(new WebPermission(NetworkAccess.Connect | NetworkAccess.Accept,
                                                        new Regex(@"http://localhost:31337/hadouken\.plugins.*")));

            // Isolated storage
            permissions.AddPermission(new IsolatedStorageFilePermission(PermissionState.Unrestricted));

            var ev = new Evidence(new EvidenceBase[] { new Url(config["Url"].ToString()) }, null);

            var fxAsm  = Assembly.LoadFile(Path.Combine(currentDirectory, FxAssembly));
            var domain = AppDomain.CreateDomain(pluginId, ev, setup, permissions,
                                                typeof(PluginHost).Assembly.Evidence.GetHostEvidence <StrongName>(),
                                                fxAsm.Evidence.GetHostEvidence <StrongName>());

            return((PluginHost)Activator.CreateInstanceFrom(
                       domain,
                       typeof(PluginHost).Assembly.ManifestModule.FullyQualifiedName,
                       typeof(PluginHost).FullName,
                       false,
                       BindingFlags.Default,
                       null,
                       new object[] { pluginId, config },
                       null,
                       null).Unwrap());
        }
Пример #11
0
        [Category("NotWorking")]          // MS bug: https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=304583
        public void FromString_Quote_Delimiter_MS()
        {
            const string    xml = "<value name='Company'>Novell</value>";
            SecurityElement se  = SecurityElement.FromString(xml);

            Assert.AreEqual("'Company'", se.Attribute("name"), "#1");
            Assert.AreEqual(string.Format(CultureInfo.InvariantCulture,
                                          "<value name=\"'Company'\">Novell</value>{0}",
                                          Environment.NewLine), se.ToString(), "#2");
        }
Пример #12
0
        private static FingerPrint LoadFingerPrint(String destFileName)
        {
            String fingerPrintFileName = FileDownloadHelper.MakeFingerPrintFilePath(destFileName);

            if (!File.Exists(fingerPrintFileName))  //记录文件尚未创建
            {
                return new FingerPrint {
                           timeStamp = "", fileSize = 0
                }
            }
            ;

            try
            {
                SecurityElement xmlDoc = SecurityElement.FromString(File.ReadAllText(fingerPrintFileName));

                String timeStamp = xmlDoc.Attributes["time_stamp"].ToString();
                Int64  fileSize  = Int64.Parse(xmlDoc.Attributes["file_size"].ToString());
                return(new FingerPrint {
                    timeStamp = timeStamp, fileSize = fileSize
                });
            }
            catch (IOException)
            {
                return(new FingerPrint {
                    timeStamp = "", fileSize = 0
                });
            }
            catch (System.IO.IsolatedStorage.IsolatedStorageException)
            {
                return(new FingerPrint {
                    timeStamp = "", fileSize = 0
                });
            }
            catch (XmlSyntaxException)
            {
                return(new FingerPrint {
                    timeStamp = "", fileSize = 0
                });
            }
            catch (FormatException)
            {
                return(new FingerPrint {
                    timeStamp = "", fileSize = 0
                });
            }
            catch (NullReferenceException)
            {
                return(new FingerPrint {
                    timeStamp = "", fileSize = 0
                });
            }
        }
Пример #13
0
 [System.Security.SecurityCritical]  // auto-generated
 public static Object XmlStringToSecurityObject(String s)
 {
     if (s == null)
     {
         return(null);
     }
     if (s.Length < 1)
     {
         return(null);
     }
     return(SecurityElement.FromString(s).ToSecurityObject());
 }
Пример #14
0
 protected override bool OnDeserializeUnrecognizedElement(string elementName, System.Xml.XmlReader reader)
 {
     if (elementName == "PermissionSet")
     {
         SecurityElement = SecurityElement.FromString(reader.ReadOuterXml());
         return(true);
     }
     else
     {
         return(base.OnDeserializeUnrecognizedElement(elementName, reader));
     }
 }
        internal System.Security.Policy.ApplicationTrust InternalGetApplicationTrust()
        {
            if (this._ApplicationTrust == null)
            {
                return(null);
            }
            SecurityElement element = SecurityElement.FromString(this._ApplicationTrust);

            System.Security.Policy.ApplicationTrust trust = new System.Security.Policy.ApplicationTrust();
            trust.FromXml(element);
            return(trust);
        }
Пример #16
0
 public void FromString_Null()
 {
     try {
         SecurityElement.FromString(null);
         Assert.Fail("#1");
     } catch (ArgumentNullException ex) {
         Assert.AreEqual(typeof(ArgumentNullException), ex.GetType(), "#2");
         Assert.IsNull(ex.InnerException, "#3");
         Assert.IsNotNull(ex.Message, "#4");
         Assert.IsNotNull(ex.ParamName, "#5");
         Assert.AreEqual("xml", ex.ParamName, "#6");
     }
 }
        public PolicyLevel CreateMediumTrustPolicy()
        {
            PolicyLevel policyLevel = PolicyLevel.CreateAppDomainLevel();
            string      contents;

            using (var file = File.OpenText(MediumTrustConfigFile))
            {
                contents = file.ReadToEnd();
            }
            SecurityElement securityElement = SecurityElement.FromString(Resources.MediumTrustConfig);

            policyLevel.FromXml(securityElement);
            return(policyLevel);
        }
 private void OnDeserialized(StreamingContext ctx)
 {
     if ((ctx.State & ~(StreamingContextStates.Clone | StreamingContextStates.CrossAppDomain)) != (StreamingContextStates)0)
     {
         if (this.m_serializedPermission != null)
         {
             this.FromXml(SecurityElement.FromString(this.m_serializedPermission));
             this.m_serializedPermission = null;
             return;
         }
         this.SecurityZone = this.m_zone;
         this.m_zone       = SecurityZone.NoZone;
     }
 }
Пример #19
0
        public void FromString_CharacterReferences()
        {
            const string xml = @"
				<value name=""name&#38;address"">Suds&#x26;Soda&#38;</value>"                ;

            SecurityElement se = SecurityElement.FromString(xml);

            Assert.IsNotNull(se, "#1");
            Assert.IsNotNull(se.Attributes, "#2");
            Assert.AreEqual("name&#38;address", se.Attribute("name"), "#3");
            Assert.AreEqual("value", se.Tag, "#4");
            Assert.AreEqual("Suds&#x26;Soda&#38;", se.Text, "#5");
            Assert.IsNull(se.Children, "#6");
        }
Пример #20
0
 private void OnDeserialized(StreamingContext ctx)
 {
     if (this.m_serializedPermission != null)
     {
         this.FromXml(SecurityElement.FromString(this.m_serializedPermission));
         this.m_serializedPermission = null;
     }
     else if (this.m_site != null)
     {
         this.m_unrestricted = false;
         this.m_sites        = new SiteString[] { this.m_site };
         this.m_site         = null;
     }
 }
        private static bool IsDataObjectFromLessPriviligedApplicationDomain(IDataObject dataObjectToApply)
        {
            bool   retVal           = false;
            object applicationTrust = null;
            // Extract the permission set in case of xaml cut and paste
            // extract permission set if it exists if not data came from full trust app and we do not care
            bool isApplicationTrustFormatPresent = false;

            isApplicationTrustFormatPresent = dataObjectToApply.GetDataPresent(DataFormats.ApplicationTrust, /*autoConvert:*/ false);
            if (isApplicationTrustFormatPresent)
            {
                applicationTrust = dataObjectToApply.GetData(DataFormats.ApplicationTrust, /*autoConvert:*/ false);
            }

            if (applicationTrust != null)
            {
                string applicationTrustText = null;
                // convert to string
                applicationTrustText = applicationTrust.ToString();


                // Convert string to permission set for getting permission set of source
                PermissionSet permissionSetSource;
                try
                {
                    SecurityElement securityElement = SecurityElement.FromString(applicationTrustText);
                    permissionSetSource = new System.Security.PermissionSet(PermissionState.None);
                    permissionSetSource.FromXml(securityElement);
                }
                catch (XmlSyntaxException)
                {
                    // This is the condition where we have Malformed XML in the clipboard for application trust
                    // here we will fail silently since we do not want to break arbitrary applications
                    // but since we cannot establish the validity of the application trust content we will fall back to
                    // whatever is more secure
                    return(true);
                }

                //extract permission set for the current appdomain which is target
                PermissionSet permissionSetDestination = SecurityHelper.ExtractAppDomainPermissionSetMinusSiteOfOrigin();
                //Compare permissions sets
                if (!permissionSetDestination.IsSubsetOf(permissionSetSource))
                {
                    retVal = true; // in case target is not subset of source revert to unicode or text
                }
            }
            return(retVal);
        }
Пример #22
0
 public void FromString_Null()
 {
     try
     {
         SecurityElement.FromString(null);
         Assert.False(true);
     }
     catch (ArgumentNullException ex)
     {
         Assert.Equal(typeof(ArgumentNullException), ex.GetType());
         Assert.Null(ex.InnerException);
         Assert.NotNull(ex.Message);
         Assert.NotNull(ex.ParamName);
         Assert.Equal("xml", ex.ParamName);
     }
 }
 private void OnDeserialized(StreamingContext ctx)
 {
     if (this.m_serializedPermission != null)
     {
         this.FromXml(SecurityElement.FromString(this.m_serializedPermission));
         this.m_serializedPermission = null;
         return;
     }
     if (this.m_url != null)
     {
         this.m_unrestricted = false;
         this.m_urls         = new URLString[1];
         this.m_urls[0]      = this.m_url;
         this.m_url          = null;
     }
 }
 public static IPermission GetPermissionFromXml(string permissionXml)
 {
     try {
         if (!String.IsNullOrEmpty(permissionXml))
         {
             SecurityElement securityElement = SecurityElement.FromString(permissionXml);
             string          typeName        = securityElement.Attribute("class");
             //string assemblyName = securityElement.Attribute("assembly");
             IPermission result = (IPermission)ReflectionHelper.CreateObject(typeName);
             result.FromXml(securityElement);
             return(result);
         }
     } catch (Exception e) {
         Tracing.Tracer.LogError(e);
     }
     return(null);
 }
Пример #25
0
    private void ParseSetting(string pContent)
    {
        try
        {
            SecurityElement setting = SecurityElement.FromString(pContent);

            AppConst.AppVersion = setting.Attribute("version");
            AppConst.ConfigURI  = setting.Attribute("server");
            AppConst.AppID      = setting.Attribute("appid");
            AppConst.AppChannel = setting.Attribute("channel");
            AppConst.AppBuild   = int.Parse(setting.Attribute("build"));
        }
        catch (Exception e)
        {
            LogUtil.LogExInfo("Read Setting Error !", e);
        }
    }
Пример #26
0
 public void FromString_Null()
 {
     try
     {
         SecurityElement.FromString(null);
         Assert.False(true);
     }
     catch (ArgumentNullException ex)
     {
         Assert.Equal(typeof(ArgumentNullException), ex.GetType());
         Assert.Null(ex.InnerException);
         if (!PlatformDetection.IsNetNative)  // .Net Native toolchain optimizes away exception messages and paramnames.
         {
             Assert.NotNull(ex.Message);
             Assert.NotNull(ex.ParamName);
             Assert.Equal("xml", ex.ParamName);
         }
     }
 }
Пример #27
0
 private void OnDeserialized(StreamingContext ctx)
 {
     if (this.m_serializedPermission != null)
     {
         this.FromXml(SecurityElement.FromString(this.m_serializedPermission));
         this.m_serializedPermission = (string)null;
     }
     else
     {
         if (this.m_site == null)
         {
             return;
         }
         this.m_unrestricted = false;
         this.m_sites        = new SiteString[1];
         this.m_sites[0]     = this.m_site;
         this.m_site         = (SiteString)null;
     }
 }
Пример #28
0
        [Test]         // bug #333699 (ugh, mostly a dup)
        public void TestToString()
        {
            SecurityElement values    = new SecurityElement("values");
            SecurityElement infoValue = new SecurityElement("value");

            infoValue.AddAttribute("name", "string");
            infoValue.Text = SecurityElement.Escape("<'Suds' & \"Soda\">!");
            values.AddChild(infoValue);
            Assert.AreEqual("<value name=\"string\">&lt;&apos;Suds&apos; &amp; &quot;Soda&quot;&gt;!</value>" + Environment.NewLine, infoValue.ToString(), "#1");
            Assert.AreEqual("<'Suds' & \"Soda\">!", infoValue.Text, "#2");
            Assert.IsNull(values.Text, "#3");

            Assert.AreEqual(String.Format("<values>{0}<value name=\"string\">&lt;&apos;Suds&apos; &amp; &quot;Soda&quot;&gt;!</value>{0}</values>{0}", Environment.NewLine), values.ToString(), "#4");

            SecurityElement sec = SecurityElement.FromString(values.ToString());

            Assert.AreEqual(1, sec.Children.Count, "#5");
            Assert.AreEqual("<'Suds' & \"Soda\">!", ((SecurityElement)sec.Children [0]).Text, "#6");
        }
Пример #29
0
        public void Load()
        {
            values = new Hashtable();
            if (!File.Exists(file))
            {
                return;
            }

            try
            {
                using (FileStream fs = File.OpenRead(file))
                {
                    StreamReader r   = new StreamReader(fs);
                    string       xml = r.ReadToEnd();
                    if (xml.Length == 0)
                    {
                        return;
                    }

                    SecurityElement tree = SecurityElement.FromString(xml);
                    if (tree.Tag == "values" && tree.Children != null)
                    {
                        foreach (SecurityElement value in tree.Children)
                        {
                            if (value.Tag == "value")
                            {
                                LoadKey(value);
                            }
                        }
                    }
                }
            }
            catch (UnauthorizedAccessException)
            {
                values.Clear();
                throw new SecurityException("No access to the given key");
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("While loading registry key at {0}: {1}", file, e);
                values.Clear();
            }
        }
        //public static byte[] SignBodyParameter(XmlDocument doc, RSA key)
        //{
        //    var responseXml = doc.GetElementsByTagName("xml")[0];

        //    var docForSign = new XmlDocument();
        //    docForSign.LoadXml(responseXml.InnerText);

        //    if (docForSign.FirstChild.Name == "xml")
        //        docForSign.RemoveChild(docForSign.FirstChild);

        //    var signedXml = new SignedXml
        //    {
        //        SigningKey = key
        //    };

        //    var objectID = docForSign.FirstChild.Name;
        //    var dataObject = new DataObject
        //    {
        //        Data = docForSign.ChildNodes,
        //        Id = objectID
        //    };

        //    signedXml.AddObject(dataObject);

        //    signedXml.AddReference(new Reference($"#{objectID}"));

        //    signedXml.ComputeSignature();

        //    //var realXml = signedXml.GetXml().OuterXml;

        //    //var el = new XElement("Root", realXml);
        //    //responseXml.InnerXml = el.LastNode.ToString();

        //    //responseXml.InnerXml = System.Web.HttpUtility.HtmlEncode(signedXml.GetXml().OuterXml);

        //    var s = System.Security.SecurityElement.Escape(signedXml.GetXml().OuterXml);


        //    responseXml.InnerText = System.Security.SecurityElement.Escape(signedXml.GetXml().OuterXml);

        //    //new XmlElement()

        //    //responseXml.InnerXml = signedXml.GetXml().OuterXml.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("&#34;", "&quot;").Replace("'", "&apos;");

        //    return signedXml.SignatureValue;
        //}

        public static (string signedEnvelope, byte[] signature) SignBodyParameter(string envelope, RSA key)
        {
            var doc = new XmlDocument();

            doc.LoadXml(envelope);
            var responseXml = doc.GetElementsByTagName("xml")[0];

            var docForSign = new XmlDocument();

            docForSign.LoadXml(responseXml.InnerText);

            if (docForSign.FirstChild.Name == "xml")
            {
                docForSign.RemoveChild(docForSign.FirstChild);
            }

            var signedXml = new SignedXml
            {
                SigningKey = key
            };

            var objectID   = docForSign.FirstChild.Name;
            var dataObject = new DataObject
            {
                Data = docForSign.ChildNodes,
                Id   = objectID
            };

            signedXml.AddObject(dataObject);

            signedXml.AddReference(new Reference($"#{objectID}"));

            signedXml.ComputeSignature();

            var securityElement = SecurityElement.FromString(envelope);

            var k = securityElement.SearchForChildByTag("s:Body").SearchForChildByTag("RegisterResponse").SearchForChildByTag("xml");

            k.Text = SecurityElement.Escape(signedXml.GetXml().OuterXml);

            return(securityElement.ToString(), signedXml.SignatureValue);
        }