C# Calculate and verify SHA256 value for SEPA (XML) paymentfile

徘徊边缘 提交于 2019-12-04 12:51:39

By looking here http://www.mobilefish.com/download/sepa_xml/pain.001.001.02.xml, it seems you were missing the xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" namespace from the Document node (probably because it was stripped by an XML parser). I have modified a little your code so that it use the using syntax and I added the namespace if missing. Now it returns the right hash.

XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.LoadXml(xml);

XmlNodeList list = doc.GetElementsByTagName("Document");

XmlElement node = (XmlElement)list[0];
node.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");

string s = node.OuterXml;

// The XmlDsigC14NTransform will strip the UTF8 BOM
using (MemoryStream msIn = new MemoryStream(Encoding.UTF8.GetBytes(s)))
{
    XmlDsigC14NTransform t = new XmlDsigC14NTransform(true);
    t.LoadInput(msIn);

    using (var hash = new SHA256Managed())
    {
        byte[] digest = t.GetDigestedOutput(hash);
        string result = BitConverter.ToString(digest).Replace("-", String.Empty);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!