小智 74
using (FileStream fs = new FileStream(@"C:\file\location", FileMode.Open))
using (BufferedStream bs = new BufferedStream(fs))
{
using (SHA1Managed sha1 = new SHA1Managed())
{
byte[] hash = sha1.ComputeHash(bs);
StringBuilder formatted = new StringBuilder(2 * hash.Length);
foreach (byte b in hash)
{
formatted.AppendFormat("{0:X2}", b);
}
}
}
Run Code Online (Sandbox Code Playgroud)
formatted包含SHA-1哈希的字符串表示形式.此外,通过使用FileStream而不是字节缓冲区,ComputeHash以块为单位计算散列,因此您不必一次性加载整个文件,这对大文件很有用.
Ben*_*key 61
使用ComputeHash方法.看这里:
示例代码段:
using(var cryptoProvider = new SHA1CryptoServiceProvider())
{
string hash = BitConverter
.ToString(cryptoProvider.ComputeHash(buffer));
//do something with hash
}
Run Code Online (Sandbox Code Playgroud)
缓冲区是文件的内容.
如果您已经将文件作为流读取,则以下技术会在您读取时计算哈希值.唯一需要注意的是,你需要消耗整个流.
class Program
{
static void Main(string[] args)
{
String sourceFileName = "C:\\test.txt";
Byte[] shaHash;
//Use Sha1Managed if you really want sha1
using (var shaForStream = new SHA256Managed())
using (Stream sourceFileStream = File.Open(sourceFileName, FileMode.Open))
using (Stream sourceStream = new CryptoStream(sourceFileStream, shaForStream, CryptoStreamMode.Read))
{
//Do something with the sourceStream
//NOTE You need to read all the bytes, otherwise you'll get an exception ({"Hash must be finalized before the hash value is retrieved."})
while(sourceStream.ReadByte() != -1);
shaHash = shaForStream.Hash;
}
Console.WriteLine(Convert.ToBase64String(shaHash));
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
43207 次 |
| 最近记录: |