Passwords should never be stored verbatim in a database, but in an encrypted way. Some databases internally offer encryption; for all the others, PHP is there to help. The crypt() function encrypts a string using Data Encryption Standard (DES). This is a one-way encryption, so there is no way back. Also, subsequent calls to crypt() result in different results. Checking Logins Using an Encrypted Password (crypt.php)<?php $pass = (isset($_GET['pass'])) ? $_GET['pass'] : ''; $encpass = '$1$FK3.qn2.$Si5KhnprsRb.N.SEF4GMW0'; if (crypt($pass, $encpass) === $encpass) { echo 'Login successful.'; } else { echo 'Login failed.'; } ?> For instance, the string 'TopSecret' is encrypted into $1$FK3.qn2.$Si5KhnprsRb.N.SEF4GMW0 (and also $1$m61.1i2.$OplJ3EHwkIxycnyePplFz0 and $1$9S3.c/3.$51O1Bm4v3cnBNOb1AECil., but this example sticks with the first one). Checking whether a value corresponds to a result from calling crypt() can be done by calling crypt() again: crypt($value, $encryptedValue) must return $encryptedValue. The preceding script checks whether a password provided via the URL matches the previous result of crypt(). Calling this script with the GET parameter pass=TopSecret succeeds in logging in; all other passwords fail.
|