Saturday, August 22, 2009

Simple Encryption in PHP

Encryption using php?


A text or a password encryption can be done very easily using the functions md5() or sha1() or crypt() in php. It's a basic need to protect the password. The first step towards it is to encrypt it.

Text Encryption Using MD5 ( RSA's MD5 Message-Digest Algorithm ):


Example:

Original Text - This is test
Encrypted Text - fe1ca9859cefff19959d57aadc17187e

code:
<?php
$var = "This is test";
$enc = md5($var);
echo "Encrypted Text - $enc";
?>
On handling password, update the encrypted password in to database.
On login request, encrypt the password entered by user and compare it with the one in db.


Text Encryption Using SHA1 ( US Secure Hash Algorithm 1 ):


Example:
Original Text - This is test
Encrypted Text - 21650e52cb7a82638b93971684f6dcfceb14c9ab

code:
<?php
$var = "This is test";
$enc = sha1($var);
echo "Encrypted Text - $enc";
?>

On handling password, update the encrypted password in to database.
On login request, encrypt the password entered by user and compare it with the one in db.

Text Encryption Using Unix DES-based encryption algorithm :


Example:
Original Text - This is test
Encrypted Text - $1$tYQu2pZ5$s7mbrcnNzKFHZCrA5SXyJ/

code:
<?php
$var = "This is test";
$enc = crypt($var); //salt be automatically generated
echo "Encrypted Text - $enc";
?>

On handling password, update the encrypted password in to database.
On login request, use encrypt() as below to validate the password.
if (crypt($input, $password) == $password) {
echo "Password verified!"; }
where $input in user posted password and $password is the encrypted one in database.