CDoc
CDoc

Reputation: 397

Get MD5 checksum of Byte Arrays' conent in C#

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.

Upvotes: 4

Views: 9264

Answers (2)

mike
mike

Reputation: 2308

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();
        }
    }

Upvotes: 1

Tim
Tim

Reputation: 6060

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

Upvotes: 11

Related Questions