如何为XML消息体创建SHA-256哈希值

时间:2011-09-16 13:08:58

标签: c# hash sha256

我正在尝试创建一个人类可读但可以验证为未经修改的XML文件。

我采取的方法如下:

  • 生成xml邮件正文(已应用规范化(C14N))
  • 生成邮件正文的哈希值(SHA-256)
  • 加密哈希值(AES-256)
  • 使用加密哈希生成邮件标头

我在此任务的每个阶段遇到问题,但当前的问题是从XML正文生成哈希值。

我得到一个异常“这个XmlReader不支持ReadContentAsBase64方法。使用CanReadBinaryContent属性来查明读者是否实现了它。”但我不知道如何实现XElement的阅读。

xml的一个例子在

之下
<?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>

以下是我一直试图无效的代码:

/// <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;
}

2 个答案:

答案 0 :(得分:2)

这就是我实施解决方案的方式。

/// <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;
}

答案 1 :(得分:1)

你不是想重新发明轮子吗?

为此目的设计了System.Security.Cryptography.Xml.SignedXml课程。