0

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, CryptoStreamMode.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

2
  • How do you add the string to the XML document? Commented Feb 17, 2011 at 19:42
  • You could return a byte[] and just let the XMLSerializer handle converting it to/from Base64. Commented Feb 17, 2011 at 19:48

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.