There is no spoon
There is no spoon

Reputation: 1796

SHA256 hash function giving unexpected result

I'm using C# and wondering why the .Net function PasswordDeriveBytes returns a different result from other SHA256 algorithums.

I'm calling it as follows:

byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
var hash = PasswordDeriveBytes("1234567890", saltValueBytes, "SHA256", 1);
byte[] SHA256Pass = hash.GetBytes();

I am expecting to get the hash c775e7b757ede630cd0aa1113bd102661ab38829ca52a6422ab782862f268646

but instead I get b????????A?n?z$?]??9,m^????@n?

I dont know what the problem is. how this function works and why the result i'm getting does not look like a SHA 256 hash.

thanks

Upvotes: 0

Views: 1166

Answers (2)

Maarten Bodewes
Maarten Bodewes

Reputation: 93948

PasswordDeriveBytes is not a hash function, it is a key derivation function. It follows PBKDF1 precisely until you exceed 20 bytes of output, for which PBKDF1 was designed. When that happens it turns into a proprietary, badly programmed, insecure and unknown key stretching function.

PBKDF1 uses SHA-1 to implement the key derivation. SHA-256 is a rather more secure hash function with a larger output. So you will never ever have the same output for both functions. If you would, you will have broken one of the two - or much more likely you will have made a mistake.

Note that you should use PBKDF2 over PBKDF1 as it is more secure and does provide key stretching.

Upvotes: 2

Jonathan Rupp
Jonathan Rupp

Reputation: 15762

How are you displaying your bytes? It looks like you took them and tried to convert them directly to a string, which gives you some wierd-looking characters (and about half the number of characters expected). See this answer for some options for doing the conversion to a hex string like it appears you were expecting.

Upvotes: 4

Related Questions