Search code examples
chashsha256crypt

How to get hex hash with crypt() function?


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!


Solution

  • 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.