Thursday, March 12, 2009

How to use MD5 and SHA1 in php (cryptography)

MD5 - Message-Digest algorithm 5
SHA1 - Secure Hash Algorithm
These are the two main inbuilt functions used in php to encrypt sensitive data.
SHA1 is now consider and recommended to be more secure than MD5.


echo md5('password'); //5f4dcc3b5aa765d61d8327deb882cf99

echo '<br /><br />';

echo sha1('password'); //5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8


If you run above code your will see the encrypted string of the word password.
You can clearly see that sha1 is longer than md5. sha1 is encrypted with more bits.

Once a value is encrypted you cannot reaverse the process. So how you gonna check the values again? check the following code.


$stored_password = sha1('my_pass');

$pass = $_POST['pass'] // input password

if($stored_password == sha1($pass))
echo 'correct password';
echo 'wrong password';


Always remember to encrypt the input data with relevant encryption method before comparing values.

No comments:

Post a Comment