You should never store user passwords in plain text, because once a hacker accesses your database, it will make it easy for him or her to get hold of your user data. You are encouraged to scramble or encrypt your passwords before sending them to your database. PHP offers a couple of methods that you can use to scramble a user’s password. One of them is one-way encryption. This basically means that a password cannot be decrypted once it is hashed. The other is to encrypt when sending them to the database, and to decrypt when retrieving them from the database. Of the two, the first one is the most secure, because hashed values are usually forty characters long and not easy to remember. PHP provides us with a function called SHA1() that calculates the hash of a string. This function takes a string parameter and has the following syntax: SHA1(Stringparameter) An example script might look something like this: <?php $string ='mystring'; echo "The hashed value for <b>".$string."</b> is: ".SHA1($string); ?> Below is a screen shot of the results for the above script:
Now, let’s write the code that checks to see if a given value matches a hash string: <?php $string ='mystring'; echo "The hashed value for <b>".$string."</b> is: ".SHA1($string); $hashedval = SHA1($string); if(SHA1($hashedval) === '9ce3ea4d6fac2165933b3971e6d5a13753c7d878') { echo "The string matches the hash value"; }else{ echo "The string does not match the hashed value"; } ?> The newly calculated value for the $string variable is stored in another variable called $hashedval. The second part of the code then tests the given hash value with the given string (mystring): $hashedval = SHA1($string); if($hashedval=== '9ce3ea4d6fac2165933b3971e6d5a13753c7d878') { echo "The string matches the hash value"; }else{ echo "The string does not match the hashed value"; } In our next article, we will build a login system that will put into practice the topics we just discussed.
blog comments powered by Disqus |
|
|
|
|
|
|
|