MD5CryptoServiceProvider creates different hashes for the same fil

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

hi im using System.Security.Cryptography.MD5CryptoServiceProvider to generate
a hash which represents an xml file that i will receive.

I receive a summary file which includes a base 64 string of the hash when
the file was sent.

Upon receipt i then take in the xml file and create it as a FileInfo then
turn the fileinfo into a file stream then use the MD5 service to compute a
hash. like this

//////////////////

MD5CryptoServiceProvider md5Provider = new MD5CryptoServiceProvider();

FileStream fs = null;

bool hashSame = false;

fs = checkFile.OpenRead();

byte[] fileHash1 = md5Provider.ComputeHash(fs);
byte[] fileHash2 = md5Provider.ComputeHash(fs);

Console.WriteLine("hash 1: " + Convert.ToBase64String(fileHash1));
Console.WriteLine("hash 2: " + Convert.ToBase64String(fileHash2));

////////////////////////////


the problem i get is that the same file generates different hashes each
time??????


can anyone help
 
Set the fs.Position back to 0 before the second call to ComputeHash. That
way both calls start at 0.
 
//////////////////

MD5CryptoServiceProvider md5Provider = new MD5CryptoServiceProvider();

FileStream fs = null;

bool hashSame = false;

fs = checkFile.OpenRead();

byte[] fileHash1 = md5Provider.ComputeHash(fs);
byte[] fileHash2 = md5Provider.ComputeHash(fs);

Console.WriteLine("hash 1: " + Convert.ToBase64String(fileHash1));
Console.WriteLine("hash 2: " + Convert.ToBase64String(fileHash2));

////////////////////////////


the problem i get is that the same file generates different hashes each
time??????

Yes - the first time you're hashing the file; the second time you're
hashing nothing, because there's nothing left to read in the stream. As
William said, reset the stream.
 
Back
Top