Search code examples
c#.netasp.net-mvcchecksum

How to get SHA1 and MD5 checksum from HttpPostedFileBase file.InputStream


I want to get the checksum of uploaded file in MVC.

Currently I am doing this

public ActionResult Index(HttpPostedFileBase file, string path)
{


    if (file != null)
    {

        string checksumMd5    = HashGenerator.GetChecksum(file.InputStream, HashGenerator.MD5);;
        string checksumSha1   = HashGenerator.GetChecksum(file.InputStream, HashGenerator.SHA1);

   //other logic follows....

    }

but when I do following in Console app and read file from File path then,

string path = @"C:\Users\anandv4\Desktop\Manifest-5977-681-673.txt";

var md5hash = HashGenerator.GetChecksum(path, HashGenerator.MD5);
var sha1 = HashGenerator.GetChecksum(path, HashGenerator.SHA1);

the values of both are different.

Code for generating hash :

public static string GetChecksum(string fileName, HashAlgorithm algorithm)
{
    using (var stream = new BufferedStream(File.OpenRead(fileName), 1000000))
    {
        return BitConverter.ToString(algorithm.ComputeHash(stream)).Replace("-", string.Empty);
    }
}

public static string GetChecksum(Stream stream, HashAlgorithm algorithm)
{
    using (stream)
    {
        return BitConverter.ToString(algorithm.ComputeHash(stream)).Replace("-", string.Empty);
    }
}

Can anyone explain me what is the difference between the two. Utlimately both the methods resolve to Stream in GetChecksum method


Solution

  • If you are hashing a stream, you need to set the current position of the stream to 0 before computing the hash.

    file.InputStream.Seek(0, SeekOrigin.Begin);
    

    For me, this is a great place for an extension method, eg.:

    //compute hash using extension method:
    string checksumMd5    = file.InputStream.GetMD5hash();
    

    Which is supported by the class:

    using System;
    using System.IO;
    
    public static class Extension_Methods
    {
    
        public static string GetMD5hash(this Stream stream)
        {
            stream.Seek(0, SeekOrigin.Begin);
            using (var md5Instance = System.Security.Cryptography.MD5.Create())
            {
                var hashResult = md5Instance.ComputeHash(stream);
                stream.Seek(0, SeekOrigin.Begin);
                return BitConverter.ToString(hashResult).Replace("-", "").ToLowerInvariant();
            }
        }
    
    }