kobra
kobra

Reputation: 4963

SHA1 hash different in Vista and XP

In a WinForm application using C#.NET 2.0 (on Vista), I am using SHA1 hash to create a hash from a string and store the hash in a text file (with UTF-8 encoding). I want to use the hash stored in text file to in a condition. When I run the project in Vista it works properly (i.e. the condition results in true), but when I run in XP the project does not run.

Is the way hash created in Vista different from XP?

Code extract

byte[] HashValue;
byte[] MessageBytes = Encoding.UTF8.GetBytes(strPlain);
SHA1Managed SHhash = new SHA1Managed();
StringBuilder strHex = new StringBuilder("");
HashValue = SHhash.ComputeHash(MessageBytes);
foreach (byte b in HashValue)
{
    strHex.AppendFormat("{0:x2}", b);
}
// storing strHex in a text file with UTF-8 encoding

Test condition

string newHash = Program.GetHash("This will be hashed.");
// GetHash() does has the same code as above, but instead of storing hash in file in return
// hash.
bool validHash = newHash.Equals(oldHash);
// old has is the one stored in file
if (validHash)
{
    // some code
}

[Edit]

The main problem is the same code works fine in Vista, but breaks down in XP. If there is some logical problem it should not work in any OS.

Thanks.

Upvotes: 1

Views: 813

Answers (3)

Marc Wittke
Marc Wittke

Reputation: 3155

How are you passing the binaries between the machines? I once encountered a hash validation problem when zipping the binaries with the maximum compression mode 7zip offers and unzipping it with winzip on the other side, when I was preparing a ClickOnce package on my machine.

Upvotes: 1

Paul Mason
Paul Mason

Reputation: 1129

I suspect that the old hash stored in the file might be incorrect. Try out a simple console application snippet on each machine. Something like:

Console.WriteLine(Program.GetHash("This will be hashed."));

If these are indeed giving the same result then it must be something to do with the comparison routine (i.e. likely oldHash mentioned above).

One other thing to note; I see you're using bool validHash to store the comparison results however checking the boolean validSource afterwards. Is this just a mistype?

Upvotes: 0

Greg Hewgill
Greg Hewgill

Reputation: 993333

I am curious why you mention UTF-8 encoding in relation to storing the hash value in a text file. Are you attempting to store the raw data bytes, somehow converted to UTF-8, or are you storing a hexadecimal representation of the hash value?

Normally when storing a hash value in a text file, you would use the hex representation, such as:

3e2f9d9069abd6ace2cb18f7390a06c034a0f9dd

There would be no need to specifically use UTF-8 encoding, since the above is plain ordinary ASCII.

Upvotes: 0

Related Questions