Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I effectively use crypt()

Tags:

php

encryption

I don't understand the documentation at php.net. 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

PHP.net documentation:

<?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!";
}
?> 

How does this work?


1 Answers

Since crypt() only uses the first two characters (or whatever CRYPT_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.

like image 116
Jeffrey Hantin Avatar answered May 04 '26 09:05

Jeffrey Hantin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!