c# - 如何从 HttpPostedFileBase file.InputStream 获取 SHA1 和 MD5 校验和

标签 c# .net asp.net-mvc checksum

我想在MVC中获取上传文件的校验和。

目前我正在做这个

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....

    }

但是当我在控制台应用程序中执行以下操作并从文件路径读取文件时,

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

两者的值不同。

生成哈希的代码:

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

谁能解释一下这两者有什么区别。最终这两种方法都解析为 GetChecksum 方法中的 Stream

最佳答案

如果您要对流进行哈希处理,您需要在计算哈希之前将流的当前位置设置为 0

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

对我来说,这是扩展方法的好地方,例如:

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

该类支持哪些:

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

}

关于c# - 如何从 HttpPostedFileBase file.InputStream 获取 SHA1 和 MD5 校验和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38876350/

相关文章:

c# - WCF/REST 将图像放入图片框?

c# - 轻松的安全 AppiumService

c# - 有没有更好的方法来使用依赖注入(inject)来实例化接口(interface)?

c# - 如何获取矩形内图像的内容?

c# - FFMPEG:用多帧解码 h264

时间:2019-03-17 标签:c#linqconditionalunion

asp.net - 当 ConcurrencyMode = Multiple 时,两个并行 WCF 请求是否可以由同一线程处理

asp.net-mvc - 无法连接到远程服务器 - jQuery 是可能的,HttpWebRequest .NET 失败

c# - 如何使 Asp.Net 服务器端路由与无哈希 url 一起工作?例如用于 Backbone/AngularJS

html - ASP NET MVC href 到图像?