Click here to Skip to main content
15,896,063 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am having troubles when trying to calculate the hash MSD5 of an XML file. I have a third party validator that calculates it correctly, i am trying to make my own validator in c# but it does not work, i keep getting an invalid hash MD5 with big xml files, with small files it works fine. The big file has around 63000 lines.

The code in C#:

C#
public string GenerateHash(string xml, string hashOrigin = null)
    {

        XDocument doc = XDocument.Parse(xml);

        StringBuilder sb = new StringBuilder();

        string pKeyEncode = doc.Root.Value;
        if (!string.IsNullOrEmpty(hashOrigin))
            pKeyEncode = pKeyEncode.Replace(hashOrigin, "");

        MD5CryptoServiceProvider _cs = new MD5CryptoServiceProvider();
        byte[] _bs = Encoding.GetEncoding("ISO-8859-1").GetBytes(pKeyEncode);
        _bs = _cs.ComputeHash(_bs);
        StringBuilder _s = new System.Text.StringBuilder();
        foreach (byte _b in _bs)
        {
            _s.Append(_b.ToString("x2").ToLower());
        }
        int a = _s.GetHashCode();
        return _s.ToString();
    }
Posted

1 solution

You are doing it wrong.

If you really have XML file, read the file as is, into array of bytes, not string. It will make your code independent on encoding.
To compute MD5 has, uses the class System.Security.Cryptography.MD5. Yes, it is abstract, but you need to get the provider instance via its factory method Create, as shown in the code sample at the end:
https://msdn.microsoft.com/en-us/library/system.security.cryptography.md5%28v=vs.110%29.aspx[^].

For the creation of MD5 class instance, please see the method Program.Main.

—SA
 
Share this answer
 
v2
Comments
Sascha Lefèvre 21-May-15 16:49pm    
+5
Sergey Alexandrovich Kryukov 21-May-15 16:49pm    
Thank you, Sascha.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900