CHAPTER 5 – Working with Passwords
Another appliance of hash functions is authenticating a password entered in a form on your web site with a password stored in your database. For obvious reasons, you don't want to store unencrypted passwords in your database. You want to prevent evil hackers who have access to your database (because the sysadmin blundered) from stealing passwords used by your clients. Because hash functions are not at all reversible, you can store the password hashed with a function like md5() or sha1() so the evil hackers can't get the password in plain text. The example Auth class implements two methods--addUser() and authUser()--and makes use of the sha1() hashing function. The table scheme looks like this:
CREATE TABLE users ( email VARCHAR(128) NOT NULL PRIMARY KEY, passwd CHAR(40) NOT NULL ); We use a length of 40 here, which is the same as the sha1() digest in hexadecimal characters: <?php class Auth { function Auth() { mysql_connect('localhost', 'user', 'password'); mysql_select_db('my_own_bookshop'); } public function addUser($email, $password) { $q = ' INSERT INTO users(email, passwd) VALUES ("'. $email. '", "'. sha1($password).'") '; mysql_query($q); } public function authUser($email, $password) { $q = ' SELECT * FROM users WHERE email="'. $email. '" AND passwd ="'. sha1($password). '" '; $r = mysql_query($q); if (mysql_num_rows($r) == 1) { return TRUE; } else { return FALSE; } } } ?> We didn't use addslashes() around the $email and $password variables earlier. We will do that in the script that calls the methods of this class: <?php /* Include our authentication class and sanitizing function*/ require_once 'Auth.php'; require_once 'sanitize.php'; * Define our parameters */ $sigs = array ( 'email' => array ('required' => TRUE, 'type' => 'string', 'function' => 'addslashes'), 'passwd' => array ('required' => TRUE, 'type' => 'string', 'function' => 'addslashes') ); /* Clean up our input */ sanitize_vars(&$_POST, $sigs); /* Instantiate the Auth class and add the user */ $a = new Auth(); $a->addUser($_POST['email'], $_POST['passwd']); /* or... we instantiate the Auth class and validate the user */ $a = new Auth(); echo $a->authUser($_POST['email'], $_POST['passwd']) ? 'OK' : 'ERROR'; ?> After the user is added to the database, something like this appears in your table: +--------+------------------------------------------+ | user | password | +--------+------------------------------------------+ | derick | 5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8 | +--------+------------------------------------------+ The first person who receives the correct password back from this sha1() hash can ask me for a crate of Kossu.