我正在计算所选文件的 MD5、MD4、SHA1、SHA256、SHA512、RIPEMD160 等。我创建了以下算法,但它有问题。
string finalHash;
byte[] buffer;
byte[] oldBuffer;
int bytesRead;
int oldBytesRead;
long streamSize;
long totalBytesRead = 0;
try
{
if (!String.IsNullOrEmpty(selectedFile))
{
_dataStream = File.OpenRead(selectedFile);
selectedFile = string.Empty;
}
foreach (var hashObject in from Control ctrl in Controls where ctrl is CheckBox && ((CheckBox)ctrl).Checked select HashObject)
{
//totalBytesRead = 0;
streamSize = _dataStream.Length;
buffer = new byte[4096];
bytesRead = _dataStream.Read(buffer, 0, buffer.Length);
totalBytesRead += bytesRead;
do
{
oldBytesRead = bytesRead;
oldBuffer = buffer;
buffer = new byte[4096];
bytesRead = _dataStream.Read(buffer, 0, buffer.Length);
totalBytesRead += bytesRead;
if (bytesRead == 0)
{
hashObject.TransformFinalBlock(oldBuffer, 0, oldBytesRead);
}
else
{
hashObject.TransformBlock(oldBuffer, 0, oldBytesRead, oldBuffer, 0);
}
hashCalculationWorker.ReportProgress((int)((double)totalBytesRead * 100 / streamSize));
} while (bytesRead != 0);
e.Result = hashObject.Hash;
finalHash = GenerateHex(hashObject.Hash);
Invoke(new MethodInvoker(() =>
{
// Get finalHash
}));
hashObject.Dispose();
}
}
catch (Exception)
{
}
private HashAlgorithm HashObject
{
get
{
if (isMD5Selected)
{
_hashObject = MD5.Create();
isMD5Selected = false;
}
else if (isMD4Selected)
{
_hashObject = MD4.Create();
isMD4Selected = false;
}
else if (isSHA1Selected)
{
_hashObject = SHA1.Create();
isSHA1Selected = false;
}
...
return _hashObject;
}
}
在上面的代码中,foreach 语句取决于选择的哈希算法的数量。它正确计算了第一个选择的哈希值,但在第二次和其他下一次迭代中它给出了错误的值。怎么了。有谁能够帮助我?提前非常感谢。