Asymmetric encryption in PHP
Most of us who are writing web application using vanilla PHP or PHP frameworks are using asymmetric encryption. md5, sha1 are asymmetric encryption algorithms. But here I am going to share an example of symmetric algorithm. I never came to this scenario to use symmetric encryption before. May be you may not need more like the asymmetric encryption. Anyways I thought of writing about it. Yes you might have guessed if not, I am talking about mcrypt_encrypt and mcrypt_decrypt, which uses a secret key to encrypt and decrypt texts. So Its pretty clear its up to you to secure the secret key used in encryption and decryption of the encrypted text to plain text. But before you can use mcrypt_encrypt and mcrypt_decrypt make sure you have mycrypt installed. You can use <?php echo phpinfo(); ?> to see if mcrypt is installed or not.
Installing mycrypt is pretty easy. You can use yum install php-mcrypt to install it and then load mcrypt module. Not to forget after installing you must restart your apache.
All set now? Ok here's the php code snippet for encryption and decryption.
Encryption
Installing mycrypt is pretty easy. You can use yum install php-mcrypt to install it and then load mcrypt module. Not to forget after installing you must restart your apache.
All set now? Ok here's the php code snippet for encryption and decryption.
Encryption
<?phpDecryption (using the above encrypted key : $encrypted_key)
if(!defined('API_SALT'))
define('API_SALT','2d32Yy');
$plaintext="plaintext";
$iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$encrypted_text = mcrypt_encrypt(MCRYPT_BLOWFISH, API_SALT, utf8_encode($plaintext), MCRYPT_MODE_ECB, $iv);
$encrypted_text=base64_encode($encrypted_text);
echo $encrypted_text;
?>
<?php
if(!defined('API_SALT'))
define('API_SALT','2d32Yy');
$iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$plaintext = mcrypt_decrypt(MCRYPT_BLOWFISH, API_SALT, base64_decode($encrypted_text), MCRYPT_MODE_ECB, $iv);
$plaintext=rtrim($plaintext);
echo $plaintext;
?>
Hope it becomes useful to you too.
Comments
Post a Comment