MD5CryptoServiceProvider creates different hashes for the same fil

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
 
W

William Stacey [MVP]

Set the fs.Position back to 0 before the second call to ComputeHash. That
way both calls start at 0.
 
J

Jon Skeet [C# MVP]

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

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top