Question

i'm creating a login system in PHP, and i'm experiencing with hashing.

Can someone tell me why if I use hash() with sha512 it generates a string of 128 chars while using crypt() with sha512 it is only 118 chars (but only 103 chars of hash) ?

Example:

$password = "password";
$hashed =   crypt($password, '$6$rounds=5000$'.core::genSalt().'$');
$hashed2 =  hash('sha512', $password);

echo "pwd hashed with hash() -> $hashed<br>";
echo "hashed pwd length? ".strlen($hashed);
echo "<br>-----<br>";
echo "pwd hashed with crypt() -> $hashed2<br>";
echo "hashed pwd length? ".strlen($hashed2);

and it results in:

pwd hashed with crypt() -> $6$rounds=5000$HGWYWN+gVBLsotI5$sxqlewzU4pn4Z0/.5DlX6orE9Mw2W0Z7VJ6Qp8cCQdDqGvCJHqgiG6fYQjI2dSm78ErfXQ8QbMjq1JCVl2Hah0 
hashed pwd length? 118

pwd hashed with hash() -> b109f3bbbc244eb82441917ed06d618b9008dd09b3befd1b5e07394c706a8bb980b1d7785e5976ec049b46df5f1326af5a2ea6d103fd07c95385ffab0cacbc86 
hashed pwd length? 128

Thank you

Was it helpful?

Solution

hash() uses an hexadecimal representation([a-f0-9]) whereas crypt() seems to use [a-zA-Z0-9./] from what I see.

For the hexadecimal representation, each character holds 4(16 needs 4 binary digits) bits of information, and for the crypt one, each character holds 6(64 needs 6 binary digits).

We know that SHA-512 generates a 512 bit hash, so:

  • hash(): 512 / 4 = 128 characters
  • crypt(): 512 / 6 = 85,33 ~= 86 characters, which matches with the character length if we strip the crypt mode, rounds, and salt($6$rounds=5000$HGWYWN+gVBLsotI5$). In your example that's "sxqlewzU4pn4Z0/.5DlX6orE9Mw2W0Z7VJ6Qp8cCQdDqGvCJHqgiG6fYQjI2dSm78ErfXQ8QbMjq1JCVl2Hah0"

As an illustration, see what happens when we use 10, 16 or 36 characters to represent a number.

$decimalNumber = 123456789;
var_dump(base_convert($decimalNumber, 10, 16), base_convert($decimalNumber, 10, 36));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top