I need to generate a HMAC for objects that I am serializing using the XMLSerializer found in the .NET framework. Each object will contain a property called "HMAC" that will contain a hash of the object's values itself but excluding the "HMAC" field. I've found this question that mentions a built-in solution within the CLR but doesn't elaborate on exactly what its called or how I go about using it?
A sample object would look something like this:
[Serializable]
[XmlRoot("request", IsNullable = false)]
public class Request
{
[XmlElement(ElementName = "hmac")]
public string Hmac { get; set; }
[XmlElement(ElementName = "nonce")]
public string Nonce { get; set; }
[XmlElement(ElementName = "expiration")]
public DateTime Expiration { get; set; }
/* A bunch of other properties to be serialized */
private Request() { }
public Request(string hmac, string nonce, DateTime expiration)
{
Hmac = hmac;
Nonce = nonce;
Expiration = expiration;
}
}
The HMAC property will need to be set as a serialization of the entire object, excluding the HMAC object itself. My first thoughts are setting up some sort of two-pass serialization, which involves:
- Setting an xmlignore property to the HMAC object on the first pass
- Serializing the entire object
- Hashing the result, and setting the value of the HMAC property
- Re-serializing the whole thing again, ready for transmission.
Is this the best way to go about it? Has anyone done anything like this before, and what have you found to be the cleanest way of going about it???