Reputation: 9384
In my application I have the following code for the encryption of some data as string:
private string EncryptPermission(User user)
{
Encoding encoding = Encoding.ASCII;
Cryptography cryptography = CreateCryptography(user);
byte[] val = encoding.GetBytes(user.Permission.ToString());
byte[] encrypted = cryptography.Encrypt(val);
string result = encoding.GetString(encrypted);
return result;
}
That works like I want. Now I want to write that data to an xml-file like:
internal void WriteUser(User user)
{
XElement userElement = new XElement("user",
new XAttribute("id", user.UserId.ToString("N")),
new XElement("name", user.Username),
new XElement("password", user.Password),
new XElement("permission", EncryptPermission(user)));
XDocument document = GetDocument();
if (document.Root != null)
{
document.Root.Add(userElement);
SaveDocument(document);
}
}
At the moment I call SaveDocument
I get an Exception
like:
A first chance exception of type 'System.ArgumentException' occurred in System.Xml.dll
Additional information: ' ', hexadecimal value 0x06, is a invalid char.
(Translated from german)
How can I solve this? I've already tried to use Converter.ToBase64String(..)
and Converter.FromBase64String(..)
but there I get an exception that the data is too long.
Upvotes: 0
Views: 315
Reputation: 15685
Encryption produces bytes, and not all bytes are valid characters, as expected by XML. Your 0x06 is just one such. One possible solution is to convert the bytes into Base64 before writing to XML. Base64 uses only valid characters, at the cost of some increase in size: it uses four characters to write three bytes.
Have a look at the Convert
class for the C# Base64 conversion methods.
Upvotes: 1
Reputation: 389
It mostly likely down to a character within the string, has broken the xml.
Add the encrypted string in a CDATA[] tags, within the nodes and you should be fine
What does <![CDATA[]]> in XML mean?
Upvotes: 0