Skip to content

Instantly share code, notes, and snippets.

@bappi-d-great
Last active June 5, 2024 08:12
Show Gist options
  • Save bappi-d-great/f5884c095b663ea90b27277f33b1e998 to your computer and use it in GitHub Desktop.
Save bappi-d-great/f5884c095b663ea90b27277f33b1e998 to your computer and use it in GitHub Desktop.
Encryption in WordPress
<?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, 0, 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 );
*
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment