(PHP) How to implement crypt () correctly

Here is an example from the PHP man page for crypt () :

<?php $password = crypt('mypassword'); // let the salt be automatically generated /* You should pass the entire results of crypt() as the salt for comparing a password, to avoid problems when different hashing algorithms are used. (As it says above, standard DES-based password hashing uses a 2-character salt, but MD5-based hashing uses 12.) */ if (crypt($user_input, $password) == $password) { echo "Password verified!"; } ?> 

Why does it work? I accept this 'mypassword' - this is the password that I want to use for the actual administrator. So I first glued and set it to $password . Obviously, I have to store this in the database. But in the following lines it uses both salt and what I'm comparing with, and I don’t understand how crypt($user_input, $password) can be equal to $password , if in this last case I ideally have the correct password as $user_input , but salty with $password compared with $password . It would be more useful for me if the last line were

 if (crypt($user_input) == $password) { echo "Password verified!"; } 

What? I do not understand?

+7
php crypt
source share
1 answer

crypt is a one-way function and returns a string that already contains salt. The result is similar to what is stored in /etc/shadow .

Example from php.net :

 <?php echo 'result: ' . crypt('somepassword'); echo 'result: ' . crypt('somepassword'); echo 'result: ' . crypt('somepassword'); ?> result: $1$K2D8DGwq$b05uO37aMwO4rnDlB9Rsi1 result: $1$aPBvu2y.$213YVEs8/5m.jMCXSScly/ result: $1$dW3Xu2p6$nuCtJe2zzlgBMLxN2oZCx/ 

When comparing user input with the crypt result, the function automatically extracts salt from the string.

+8
source share

All Articles