开发者

problem with hexadecimal values in xml document

I have simple C# function which takes one string encode it and return it:

    public static string EncodeString(string input)
    {
        byte[] bChiperText = null;

        RijndaelManaged rp = new RijndaelManaged();
        rp.Key = UTF8Encoding.UTF8.GetBytes("!Lb!&*W_4Xc54_0W");
        rp.IV = UTF8Encoding.UTF8.GetBytes("6&^Fi6s5SAKS_Ax6");

        ICryptoTransform re = rp.CreateEncryptor();

        byte[] bClearText = UTF8Encoding.UTF8.GetBytes(input);
        MemoryStream Mstm =  new MemoryStream();

        CryptoStream Cstm = new CryptoStream(Mstm, re, Crypto开发者_开发百科StreamMode.Write);

        Cstm.Write(bClearText, 0, bClearText.Length);
        Cstm.FlushFinalBlock();

        bChiperText = Mstm.ToArray();

        Cstm.Close();
        Mstm.Close();


        return System.Text.ASCIIEncoding.ASCII.GetString(bChiperText);
   } 

After call this function with parameter "hello" i get xml file like this:

  <?xml version="1.0" encoding="utf-8"?>
  <users>
      <user name="user1" password="?V?Py????%??&#x13;?9?"/>
  </users>

Everithing fine but when i open the xml file in visual studio 2010 i receive warning like this:

Error 1 Character ' ', hexadecimal value 0x13 is illegal in XML documents.

Can anybody tell what i have done wrong?can i ignore those warnings?

Thanks


This is the problem:

return System.Text.ASCIIEncoding.ASCII.GetString(bChiperText);

You're converting arbitrary binary data to text just by treating it as if it were ASCII. It's not. Don't do that.

The safest approach is to use Base64:

return Convert.ToBase64String(bChiperText);

Of course, your client will need to do the same in revert, e.g. by using Convert.FromBase64String.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜