Sunday, November 7, 2010

10:19 PM

I’ve noticed that many of my friends are storing password in database without encrypting them. This is really a bad technique because if somebody who has access of the database can easily know the password of the particular person.


The best functions available in PHP for encryption are md5() and sha1(). These both are one way encryping mechanism i.e the string encrypted with md5() or sha1() can’t be decrypted to original string. You might be then wondering how to validate the original string with the encrypted string then you can do this by encrypting the original string and compare both string,

$string='roshan'; //this is original string
$encrypted='d6dfb33a2052663df81c35e5496b3b1b'; //which is md5('roshan')
if(strcmp(md5($string),$encrypted)==0)
  echo"Valid string";
else
  echo"Invalid string";

md5() and sha1() provides the same functinality of encryption in php but they differ in a simple way that md5() generates 32 characters of encrypted string which sha1() generates same of 40 characters.Now let’s look at the different scenario where you need to store the password encrypted in the database and you need to send the originalpasword to the member of your website. In this situation, you can’t use md5() or sha1() because you need to reset the password once if forget it. Now at this time functions like base64_encode() and gzdeflate() comes handy.You can decrypt the password encrypted with base64_encode() with base64_decode() and the same applies for gzdeflate() with gzinflate().

For those guyz who really wants to encrypt and store the password with their own encryption and decryption mechanism then here is the function i’ve used in some of my web projects.

//function to encrypt the string
function encode5t($str)
{
  for($i=0; $i<5;$i++)
  {
    $str=strrev(base64_encode($str)); //apply base64 first and then reverse the string
  }
  return $str;
}
//function to decrypt the string
function decode5t($str)
{
  for($i=0; $i<5;$i++)
  {
    $str=base64_decode(strrev($str)); //apply base64 first and then reverse the string}
  }
  return $str;
}

In this function, i’ve encrypted the string 5 times with base64_encode and reversing the string with strrev() and for decrypting 5 times by reversing the string first then applying base64_decode() .

0 comments: