Elad Lachmi
Elad Lachmi

Reputation: 10561

SHA1 hash translated to invalid xml

I have a dictionary, which I turn in to XML and then hash with SHA1.

string xmlMessageCode = inputDictionary.ToXML(); //Extension method.

UnicodeEncoding UE = new UnicodeEncoding();
SHA1Managed hasher = SHA1Managed();
byte[] hashString = Encoding.UTF8.GetBytes(xmlMessageCode.ToCharArray());
byte[] hashCode = hasher.ComputeHash(hashString);

string computedHashString = UTF8Encoding.UTF8.GetString(hashCode);

return computedHashString;

After that I put the value in an object property and then serialize a collection of these objects to XML:

XmlSerializer ser = new XmlSerializer(typeof(T));
XmlWriterSettings settings = new XmlWriterSettings()
{
Indent = false,
OmitXmlDecleration = false,
Encoding = Encoding.UTF8
};

using(StringWriter sr = new StringWriter)
{
using(XmlWriter xmlr = XmlWriter.Create(sr, settings))
{
ser.Serialize(sr, newList);
}
return sr.ToString();
}

This produces XML, but when I try to validate the resulting XML, I get an error inside the property which was created from the hashed string.

What would be the best way to resolve this? Should I strip the invalid characters or is there a more elegant solutions?

Upvotes: 0

Views: 591

Answers (1)

Robert
Robert

Reputation: 42710

XML is a text based representation - you can not embed binary information directly into it.

Therefore you have to convert the binary data to a text - usually Base64 encoding is used for that purpose.

hence instead of

string computedHashString = UTF8Encoding.UTF8.GetString(hashCode);

you should use

string computedHashString = System.Convert.ToBase64String(hashCode);

Upvotes: 2

Related Questions