TeamWild
TeamWild

Reputation: 2550

How to create SHA-256 hash value for an XML message body

I'm trying to create an XML file that is human readable but can be verified as being unmodified.

The approach I am taking is as follows:

I'm hitting problems at every stage of this task but the current issue is generating the hash value from the XML body.

I get an exception "ReadContentAsBase64 method is not supported on this XmlReader. Use CanReadBinaryContent property to find out if a reader implements it." but I don't know how else to implement the reading of the XElement.

An example of the xml is below

<?xml version="1.0" encoding="UTF-8"?>
<Application>
    <MessageHeader>
        <MessageID>00000001</MessageID>
        <MessageCheck>
            dHPHxMJGgDCHtFttgPROo24yi+R1RGx6Ahno2r0nV7zrcgR2+BX4f+RmNCVCsT5g
        </MessageCheck>
    </MessageHeader>
    <MessageBody>
        <Receipt>
            <Status>OK</Status>
            <FormReference>E00000000001</FormReference>
        </Receipt>
    </MessageBody>
</Application>

And here is the code I've been trying to get working to no avail:

/// <summary>
/// Convert the message body into a Hash value
/// </summary>
/// <param name="MessageBody">XElement holding all the message body XML nodes</param>
/// <returns>a base 64 string representing the hash code</returns>
private string GenerateMessageBodyHash(XElement MessageBody)
{
    string hash = string.Empty;
    try
    {
        // Convert the XElement into a stream of data
        using (XmlReader xr = MessageBody.CreateReader())
        {
            // Now that we have a reader, lets read the data into a byte array
            List<byte> dataList = new List<byte>();

            byte[] buffer = new byte[1000];
            int fileIndex = 0;
            int bytesRead = 0;

            while ((bytesRead = xr.ReadContentAsBase64(buffer, fileIndex, buffer.Length)) != 0 )
            {
                // Update the position into the file
                fileIndex += bytesRead;

                //add the data into the list
                dataList.AddRange(buffer);

                // reset the buffer
                buffer = new byte[1000];
            }

            SHA256 shaM = new SHA256Managed();
            hash = Convert.ToBase64String( shaM.ComputeHash( dataList.ToArray() ) );
        }
    }
    catch (Exception ex)
    {
        // TODO: Add some logging in here
    }

    return hash;
}

Upvotes: 1

Views: 7401

Answers (2)

Wiktor Zychla
Wiktor Zychla

Reputation: 48279

Aren't you trying to reinvent the wheel?

There's the System.Security.Cryptography.Xml.SignedXml class designed for such purposes.

Upvotes: 1

TeamWild
TeamWild

Reputation: 2550

This is how I implemented the solution.

/// <summary>
/// Convert the message body into a Hash value
/// </summary>
/// <param name="MessageBody">XElement holding all the message body XML nodes</param>
/// <returns>a base 64 string representing the hash code</returns>
private string GenerateMessageBodyHash(XElement MessageBody)
{
    string hash = string.Empty;
    try
    {
        using( MemoryStream ms = new MemoryStream() )
        {
            XmlWriterSettings xws = new XmlWriterSettings();
            xws.OmitXmlDeclaration = true;
            xws.Indent = false;

            using( XmlWriter xw = XmlWriter.Create( ms, xws ))
            {
                // Assign the xml to be written to the writer and then memory stream
                MessageBody.WriteTo(xw);

                SHA256 shaM = new SHA256Managed();
                hash = Convert.ToBase64String(shaM.ComputeHash( ms ));
            }
        }
    }
    catch (Exception ex)
    {
        Log.WriteLine(Category.Warning, "Exception detected generating the XML hash", ex);
    }

    return hash;
}

Upvotes: 2

Related Questions