加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在C#中安全地解析XML

发布时间:2020-12-15 21:02:43 所属栏目:百科 来源:网络整理
导读:我有一个C#应用程序,它接收来自外部服务的字节数组,表示UTF-8编码的 XML消息.这个 XML数据包含我不希望存储在字符串对象中的敏感数据,因为字符串是不可变的,当我完成它时我无法擦除这些值.我目前正在使用System.XML.XmlReader将值解析为字符串(请参阅下面的
我有一个C#应用程序,它接收来自外部服务的字节数组,表示UTF-8编码的 XML消息.这个 XML数据包含我不希望存储在字符串对象中的敏感数据,因为字符串是不可变的,当我完成它时我无法擦除这些值.我目前正在使用System.XML.XmlReader将值解析为字符串(请参阅下面的代码).如果没有我的代码(或我调用的代码)将敏感数据存储为字符串,我怎么能这样做呢?

byte[] messsage = Encoding.UTF8.GetBytes(request);
        // Send message to the server. 
        sslStream.Write(messsage);
        sslStream.Flush();

        // read the response
        byte[] buffer = new byte[2048];
        StringBuilder messageData = new StringBuilder();
        int bytes = -1;
        do
        {
            bytes = sslStream.Read(buffer,buffer.Length);

            // Use Decoder class to convert from bytes to UTF8
            // in case a character spans two buffers.
            Decoder decoder = Encoding.UTF8.GetDecoder();
            char[] chars = new char[decoder.GetCharCount(buffer,bytes)];
            decoder.GetChars(buffer,bytes,chars,0);
            messageData.Append(chars);
            // Check for ending tag.
            if (messageData.ToString().IndexOf(expectedEndTag) != -1)
            {
                break;
            }
        } while (bytes > 0);

        string response = messageData.ToString();

        using (XmlReader reader = XmlReader.Create(new StringReader(response)))
        {
            reader.ReadToFollowing("Success");
            string successVal = reader.ReadElementContentAsString();
            success = bool.Parse(successVal);
        }

解决方法

基于答案,并且鉴于字符串是不可变的,您应该编写自己的使用char []的XML解析器.完成解析后,擦除char数组内容.要在程序中使用敏感数据,请使用 SecureString作为@Ga berber和评论中建议的@Mumbo.

它很难并且重复工作,但是这样你就可以确保在解析后立即擦除内存.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读