Page 1 of 1

Understanding crypt()

Posted: Wed Jan 19, 2005 9:45 pm
by wyred
I was reading the following article when I got confused.

Article: http://www.devshed.com/c/a/PHP/Using-th ... unction/2/

Firstly, the following password was stored in the database after encrypting:

Code: Select all

$pwrd = crypt(trim("$_POSTїpword]"));

//$pwrd will be stored into the database and $_POSTїpword] is the password from the registration form.
When verifying the password received from a login form with the one in the database:

Code: Select all

if(crypt($pwrd,$rowїpword]) == $rowїpword])

//Where $pwrd is the password from the login form, $rowїpword] is the crypted password from the database.
What I'm confused is, how is the encrypted password in the database, without a salt provided (first code), be the same as the encrypted password with a salt provided? (second code)

Posted: Mon Jan 24, 2005 1:15 am
by wyred
bump

Posted: Mon Jan 24, 2005 11:34 am
by magicrobotmonkey
The 'salt" is the password itself.

Posted: Mon Jan 24, 2005 7:17 pm
by wyred
Ok, what I'm asking is, how is the following equation valid?

$pass = 'somepass';
$pass2 = 'somepass';

(crypt($pass2,crypt($pass)) == crypt($pass)) === true

Posted: Mon Jan 24, 2005 8:52 pm
by ast3r3x
crypt uses a random salt if you don't provide one. So...
crypt($pass1) != crypt($pass1);

but if you wanted...
md5($pass1) == md5($pass1);

Now of course you want your files encrypted instead of just hashed with md5, so what I would suggest is using part of the password as the salt

crypt($pass1, substr($pass1, 2));

That way it'll be the same every time and only if the password is right will it work. Hope that helps...and I hope I didn't lie to you about anything because I'm not a genius.

Posted: Mon Jan 24, 2005 9:13 pm
by ast3r3x
I didn't answer your question. Sorry.

Posted: Mon Jan 24, 2005 11:46 pm
by magicrobotmonkey
The standard DES-based encryption crypt() returns the salt as the first two characters of the output. It also only uses the first eight characters of str, so longer strings that start with the same eight characters will generate the same result (when the same salt is used).
and
If you are using the supplied salt, you should be aware that the salt is generated once. If you are calling this function repeatedly, this may impact both appearance and security.
(from http://us2.php.net/manual/en/function.crypt.php)

I think means that this:
$pass = 'somepass';
$pass2 = 'somepass';

(crypt($pass2,crypt($pass)) == crypt($pass)) === true
should work fine

Posted: Tue Jan 25, 2005 8:44 pm
by wyred
I get it now, thanks. :)