For a secured system, most of the data is encrypted in server end and sent to database. And after fetching the data from database, just decrypt before showing in front end.

There are lots of procedure to encrypt the data, lots of encryption algorithm out there. But, here we will use a simple encryption method though it’s powerful 🙂

We are going to use mcrypt library of php for this method. You can install the library following the instruction below: (based on Ubuntu)

Once you install mcrypt, you are free to use the library. Here is the code that you need to include in your project:

<?php
/**
* Protect direct access
*/
// This line is for WordPress
if ( ! defined( 'ABSPATH' ) ) die( 'Sorry cowboy! This is not your place' );
if( ! defined( 'SOME_RANDOM_STRING' ) ) define( 'SOME_RANDOM_STRING', 'ABHgtu^77y&6tgJy' );
if( ! class_exists( 'Helper_Encryption' ) )
{
/**
* Helper_Encryption
*/
class Helper_Encryption
{
private $_key;
private $_iv;
static private $_instance;
protected function __construct()
{
$this->_key = pack( 'H', SOME_RANDOM_STRING );
$this->_iv = mcrypt_create_iv(
mcrypt_get_iv_size( MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC ),
MCRYPT_DEV_URANDOM
);
}
public static function get_instance () {
if ( ! isset( self::$_instance ) ) self::$_instance = new self();
return self::$_instance;
}
public function encode( $string )
{
return base64_encode(
$this->_iv .
mcrypt_encrypt(
MCRYPT_RIJNDAEL_256,
hash( 'sha256', $this->_key, true ),
$string,
MCRYPT_MODE_CBC,
$this->_iv
)
);
}
public function decode( $encrypted )
{
$data = base64_decode( $encrypted );
$iv = substr( $data, , mcrypt_get_iv_size( MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC ) );
return rtrim(
mcrypt_decrypt(
MCRYPT_RIJNDAEL_256,
hash( 'sha256', $this->_key, true ),
substr( $data, mcrypt_get_iv_size( MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC ) ),
MCRYPT_MODE_CBC,
$iv
),
"\0"
);
}
}
}
/**
* Usage:
*
* $e = Helper_Encryption::get_instance();
* $str = 'Hello Mars!';
* $t = $e->encode( $str );
* $e->decode( $t );
*
*/
view raw encrypt.php hosted with ❤ by GitHub

The usage is already in the above gist. But again, just instantiate the class, pass the data you want to encrypt, do whatever you want. Then when needed, fetch and decrypt:

You may also read:  Why you shouldn’t use one click installer to install wordpress

Happy coding! 🙂

Leave a Reply