19 Nov 2012
encrypt decrypt in php
encrypt decrypt in php
Here i’m going to show how to wright a simple encrypt decrypt in php.
encryption/decryption is using widely to secure the data so in web programming.
It is very necessary to secure a confidential data.
We all know we can use md5 or sha or any algorithm for encrypting a text.
But the drawback of this method is it is one side. That means we can only encrypt the data. ie encrypted data cannot be decrypted.
In php we can use
mcrypt_encrypt
for encrypt a password and
mcrypt_decrypt
for decrypt a password
So let us create a simple class for encrytp/decrypt a password in php
class encdec{
//for encrypting the pawwword or any other data
function encrypt($data,$key){
$encrypted_text = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $data, MCRYPT_MODE_CBC, md5(md5($key))));
return $encrypted_text;
}
//for decrypting the pawwword or any other data
function decrypt($data,$key){
$decrypted_text = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($data), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
return $decrypted_text;
}
}
//usage
$data=new encdec();
echo $enc=$data->encrypt('hai','key');
echo "</br>";
echo $dec=$data->decrypt($enc,'key');