[英]How to get SHA1 and MD5 checksum from HttpPostedFileBase file.InputStream
I want to get the checksum of uploaded file in MVC.我想在 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
最终这两种方法都解析为GetChecksum方法中的 Stream
If you are hashing a stream, you need to set the current position of the stream to 0 before computing the hash .如果要对流进行散列,则需要在计算散列之前将流的当前位置设置为 0 。
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();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.