php - How do I effectively use crypt()


I don't understand the documentation at It appears they are using the encrypted version of password as the salt when testing against the original encryption.

When I insert crypt with out the optional second parameter (the salt) I get different encrypted versions of the same password. Is this expected behavior?

However if I insert a second parameter of 'd4' then I get the same encrypted passwords for the same password input. Expected behavior.

Prior to insertion on signup:

$pass = crypt('$pass', 'd4'); // after this I insert $pass into the mysql table

Testing on signin:

$pass = crypt($pass, 'd4'); // after this I test $pass against the mysql table documentation:

$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!";

How does this work?




Sincecrypt() only uses the first two characters (or whateverCRYPT_SALT_LENGTH is) of the salt argument, passing in the encrypted password (of which the first characters are the salt originally used to encrypt it) does the right thing.

If no salt argument is passed in, a random salt is generated and used.




If your question is... Is it normal that with certain encryption ciphers you are returned with different encrypted strings for the same password/input? The answer is yes. Not to sure what you are refering to about salt. Salt it just salt. In the end it is a deturant and means nothing. Using passwords or encrypted forms of passwords as salt is not recommended, but using some random hash (base64) of a phrase is commonly used. Let me know if this doesn't any, and I'll try again.

People are also looking for solutions to the problem: str replace - strip all unnecessary spaces in a php string


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.