简体   繁体   中英

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

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM