Convert MD5 from file to string

2

What I'm trying to do is compare the md5 obtained from a file downloaded locally, with that from a server response. The function Md5() It gets a string without any problem something like: 0A3958F9FCBA646A2D38412A3B9FC650 but the problem is that when comparing Comprobar() always returns false and when printing md5.ComputeHash(stream).ToString() I get System.Byte[] .

public bool Comprobar(string filename)
{
    using (var md5 = MD5.Create())
    {
        using (var stream = File.OpenRead(filename))
        {
            if (Md5() == md5.ComputeHash(stream).ToString())
            {
                return true;
            }
            return false;
        }
    }
}
    
asked by iuninefrendor 08.12.2018 в 18:42
source

2 answers

2

Edited: add .Replace ("-", "") to work correctly ( iuninefrendor)  I had that problem: use the bitconverter: also I do not have very clear that it is "Md5 ()" but I guess it is the md5 that you already have in string format

{
    using (var md5 = MD5.Create())
    {
        using (var stream = File.OpenRead(filename))
        {
            if (Md5() == BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", ""))
            {
                return true;
            }
            return false;
        }
    }
}
    
answered by 08.12.2018 / 21:13
source
0

According to how you apply the encoding of the array byte that returns the hash you will have a string that can vary.

If we rely on this article

HOW : Calculate and compare hash values using C # .NET

You will see the definition

static string ByteArrayToString(byte[] arrInput)
{
    int i;
    StringBuilder sOutput = new StringBuilder(arrInput.Length);
    for (i=0;i < arrInput.Length -1; i++)
    {
        sOutput.Append(arrInput[i].ToString("X2"));
    }
    return sOutput.ToString();
}

which you would use

byte[] byteArrayHash = md5.ComputeHash(stream);

string stringHash = ByteArrayToString(byteArrayHash);

if (Md5() == stringHash)
{
}

but I stress that it depends on how you apply the conversion to string in Md5() the strings may not be the same

    
answered by 09.12.2018 в 01:26