我的文本文件说快速的棕色狐狸跳过懒狗,但是当我尝试从这个文件中获取哈希值时,md5和sha1都与wikipedias结果不同.我有3个问题.1)我在代码中做错了什么?2)我怎样才能更好地使用这段代码?(我需要初始化)3)我如何加盐?
{
const int bufSize = 1024 * 8;
int read;
byte[] buf = new byte[bufSize];
string fn = @"b.txt";
byte[] result1 = new byte[0];
byte[] result2 = new byte[0];
SHA1 sha = new SHA1CryptoServiceProvider();
MD5 md5 = new MD5CryptoServiceProvider();
sha.Initialize();
md5.Initialize();
FileStream fin = File.OpenRead(fn);
while ((read = fin.Read(buf, 0, buf.Length)) != 0)
{
result1 = sha.ComputeHash(buf);
result2 = md5.ComputeHash(buf);
}
fin.Close();
MessageBox.Show(myFunc(result1));
MessageBox.Show(myFunc(result2));
}
Run Code Online (Sandbox Code Playgroud)
(编辑:现在处理哈希算法.我怀疑这是不必要的,但这是很好的做法:)
您正在为整个缓冲区调用ComputeHash,即使您只应对已读取的缓冲区部分进行哈希处理.此外,您正在为每次调用Read计算一个新哈希.
这里有一些非常简单的代码来计算哈希值:
using System;
using System.IO;
using System.Security.Cryptography;
class Test
{
static void Main()
{
byte[] plaintext = File.ReadAllBytes("b.txt");
using (MD5 md5 = MD5.Create())
{
byte[] md5Hash = md5.ComputeHash(plaintext);
Console.WriteLine(BitConverter.ToString(md5Hash));
}
using (SHA1 sha1 = SHA1.Create())
{
byte[] sha1Hash = sha1.ComputeHash(plaintext);
Console.WriteLine(BitConverter.ToString(sha1Hash));
}
}
}
Run Code Online (Sandbox Code Playgroud)
这给出了维基百科的结果 - 注意不b.txt应该在它的末尾有换行符.
获取二进制数据的另一种方法是:
byte[] plaintext = Encoding.ASCII.GetBytes(
"The quick brown fox jumps over the lazy dog");
Run Code Online (Sandbox Code Playgroud)
请注意,这只是一次计算哈希的简单方法.如果你想以流式方式(即你读取一些数据,将其添加到哈希,读取更多数据等),那么你可以使用ComputeHash(Stream)重载或(如果你想"推送"数据)你可以使用TransformBlock和TransformFinalBlock,像这样:
using System.Text;
class Test
{
static void Main()
{
using (MD5 md5 = MD5.Create())
using (SHA1 sha1 = SHA1.Create())
using (Stream input = File.OpenRead("b.txt"))
{
// Artificially small to make sure there's
// more than one read
byte[] buffer = new byte[4];
int bytesRead;
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
{
md5.TransformBlock(buffer, 0, bytesRead, null, 0);
sha1.TransformBlock(buffer, 0, bytesRead, null, 0);
}
md5.TransformFinalBlock(buffer, 0, 0);
sha1.TransformFinalBlock(buffer, 0, 0);
Console.WriteLine(BitConverter.ToString(md5.Hash));
Console.WriteLine(BitConverter.ToString(sha1.Hash));
}
}
}
Run Code Online (Sandbox Code Playgroud)
请注意我们传递的方式null,TransformBlock因为我们不需要任何输出,并且我们不会转换最终块中的任何数据.我怀疑这是你想要使用的例子,基于你以前的评论.