4

If i create a SHA-256 has in the terminal i get a nice looking hex hash:

echo -n ChillyWilly | sha256sum
4c74e3994a247dfc31a515721528c78bb6ec09ccdcfd894d09f4aa44131393a8  -

If i try to do the same with the crypt(3) function then i get something entirely different:

const char* what = crypt("ChillyWilly", "$5$");
printf("%s\n", what);
$5$$fQITOGYPwBrwOSpjX1Uhx5Ock/J84zbrqmTtg/SlvMB

It looks like Base64 but it's not.

My assumption is that if the key and salt are equal then i should get the same result. All SHA-256 hashers in the web will generate the same result from the same key/salt combination.

How can i get the same hex hash with the crypt(3) function? I have set the $5$ as instructed on the crypt manpage that should force the crypt function into SHA-256 mode.

I know there are a few similar questions here but they did not seem to contain the correct answers.

Thanks!

ele lont
  • 469
  • 1
  • 4
  • 11
  • 6
    You want `sha256` to generate the same hash as `crypt`? Why? They're different algorithms. –  Feb 11 '20 at 16:04
  • The manpage warning on `crypt` is funny. "Exhaustive searches of this key space are possible using massively parallel computers.". We'd call that an iGPU these days, and consider them unsuitable for serious gaming :D. There's a reason we moved to `sha256`. – MSalters Feb 11 '20 at 16:15
  • 1
    Yes, i did expect the same result. That's what the $5$ is there for. This should force the crypt function to generate a SHA256 hash. Assuming that the key and salt are the same i should get the same result. – ele lont Feb 12 '20 at 09:09
  • @elelont Ah, I see now. Yes, this makes sense to me now. –  Feb 12 '20 at 18:18

2 Answers2

4

While crypt can use SHA-256 when in $5$ mode, they aren't the same thing.

SHA-256 is a hash function, designed to run quickly. But crypt is a key-derivation function intended for hashing passwords. As such, it runs SHA-256 a large number of times (5000 by default) to make it slower and less prone to brute-force attacks. So it will give a different result than a simple SHA-256 use. You can see the details of the algorithm here.

As you saw, crypt also doesn't output the result as hex, but as a Base64-like encoding (not the standard Base64 but based on a similar idea). There's no point in trying to convert to hex if you do this expecting to get the same result as SHA-256.

interjay
  • 107,303
  • 21
  • 270
  • 254
2

crypt() will in fact use the same SHA-256 algorithm - but it does not return the hash as you would expect. After computing the hash it does it applies another transformation to the result, as seen here.

So I wouldn't count on using it and getting the same result as sha256sum, since it's built for a different purpose. You might look into using the openssl SHA256 implementation, or something else if you need it to match.

doggie_breath
  • 782
  • 1
  • 6
  • 21