我正在爲所選文件計算MD5,MD4,SHA1,SHA256,SHA512,RIPEMD160等。 我已經創建了以下算法,但它有問題。C#中的哈希計算
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語句取決於所選散列算法的數量。它會正確計算第一個選定的散列值,但是在第二個和其他下一個迭代中它會給出錯誤的值。 什麼錯了。有誰能夠幫助我? 非常感謝。
乍一看,你沒有重置你的'_dataStream' ... – 2012-07-12 15:14:58
關閉我的頭頂,你沒有正確地重置你的變量和數據流。 – KingCronus 2012-07-12 15:15:21
@KingCronus每次迭代都需要獲取_dataStream嗎? – 2012-07-12 15:30:24