Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get MD5 checksum of Byte Arrays' conent in C#

Tags:

c#

md5

I wrote a script in Python which gives me an MD5 checksum for a byte array's content.

strz = xor(dataByteArray, key)
m = hashlib.md5()
m.update(strz)

I can then compare a hardcoded MD5 with m like so:

if m.hexdigest() == hardCodedHash:

Is there a way to do the same thing with C#? The only resources i've found so far are not clear enough.

like image 231
CDoc Avatar asked Sep 20 '25 15:09

CDoc


2 Answers

Here's how you compute the MD5 hash

byte[] hash;
using (var md5 = System.Security.Cryptography.MD5.Create()) {
    md5.TransformFinalBlock(dataByteArray, 0, dataByteArray.Length);
    hash = md5.Hash;
}

you would then compare that hash (byte by byte) to your known hash

like image 95
Tim Avatar answered Sep 22 '25 08:09

Tim


public static string GetMD5checksum(byte[] inputData)
    {

        //convert byte array to stream
        System.IO.MemoryStream stream = new System.IO.MemoryStream();
        stream.Write(inputData, 0, inputData.Length);

        //important: get back to start of stream
        stream.Seek(0, System.IO.SeekOrigin.Begin);

        //get a string value for the MD5 hash.
        using (var md5Instance = System.Security.Cryptography.MD5.Create())
        {
            var hashResult = md5Instance.ComputeHash(stream);

            //***I did some formatting here, you may not want to remove the dashes, or use lower case depending on your application
            return BitConverter.ToString(hashResult).Replace("-", "").ToLowerInvariant();
        }
    }
like image 32
mike Avatar answered Sep 22 '25 07:09

mike