Tuesday, February 5, 2013

PHP Password Protection By Encryption

The Encryption

Say a user signs up to your site and he/she enters the password “iLoveDogs”, the way you would encrypt the password would be the following.
<?php

 $password="iLoveDogs";

$salt="onlyIKnowThis";

$encryptedPassword=crypt($password,$salt);

// SQL Stuff: save $encryptedPassword to database here
?>

See If Passwords Match

And the way you would check to see if the passwords match would be this:
<?php

 $password="iLoveDogs";

$salt="onlyIKnowThis";

$encryptedPassword=crypt($password,$salt);

// SQL Stuff: extract password from database and save to $passwordFromDatabase here
if($passwordFromDatabase==$encryptedPassword)
{
   // passwords match
}
else
{
  // passwords do not match
}
?>

What Is Salt?

You are probably wondering how we ever got minerals mixed up with web development. The salt servers as an extra "condiment" to encrypt the password even further, think of it as a door having two keys holes one of which is the salt in this case.

If somebody gained access to the passwords in the database and figured out the encrypt() algorithm they would still have to know the salt, so keep it in a safe place!
For more info on how crypt() works check out its page.

No comments:

Post a Comment