This topic is locked

More Secure Data encryption

12/14/2015 4:47:58 AM
PHPRunner Tips and Tricks
romaldus author

Article source : https://www.warpcond...el-256-and-cbc/
Requirement: PHP 5.3 +
Use the following code In Phprunner, After Application Initialized:



// Define a 32-byte (64 character) hexadecimal encryption key

// Note: The same encryption key used to encrypt the data must be used to decrypt the data
define('ENCRYPTION_KEY', 'd0a7e7997b6d5fcd55f4b5c32611b87cd923e88837b63bf2941ef819dc8ca282');
// Encrypt Function

function mc_encrypt($encrypt, $key){

$encrypt = serialize($encrypt);

$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC), MCRYPT_DEV_URANDOM);

$key = pack('H*', $key);

$mac = hash_hmac('sha256', $encrypt, substr(bin2hex($key), -32));

$passcrypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $encrypt.$mac, MCRYPT_MODE_CBC, $iv);

$encoded = base64_encode($passcrypt).'|'.base64_encode($iv);

return $encoded;

}
// Decrypt Function

function mc_decrypt($decrypt, $key){

$decrypt = explode('|', $decrypt.'|');

$decoded = base64_decode($decrypt[0]);

$iv = base64_decode($decrypt[1]);

if(strlen($iv)!==mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC)){ return false; }

$key = pack('H*', $key);

$decrypted = trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $decoded, MCRYPT_MODE_CBC, $iv));

$mac = substr($decrypted, -64);

$decrypted = substr($decrypted, 0, -64);

$calcmac = hash_hmac('sha256', $decrypted, substr(bin2hex($key), -32));

if($calcmac!==$mac){ return false; }

$decrypted = unserialize($decrypted);

return $decrypted;

}


Note:

  • Use your own Hex for ENCRYPTION KEY. You can generate Hex from here : http://www.andrewsco...m/tools/wep.asp
  • In your database, make sure your field size is enough to store encrypted data (varchar, 180 or 200 is enough)
    In PHPRunner Events :
    Add Page: Before Record Added

    Edit Page: Before Record Updated

    Import Page: Before insert Record

    Use the following code to encrypt data:

$values["YOUR_FIELD_NAME"] = mc_encrypt($values["YOUR_FIELD_NAME"], ENCRYPTION_KEY);


[color="#0000ff"]Print Page: Before Record Processed
[color="#0000ff"]Export Page: Before [size="2"]Export [/size][size="2"]Record [/size]

Use the following code to decrypt data:

$data["YOUR_FIELD_NAME"]=mc_decrypt($data["YOUR_FIELD_NAME"], ENCRYPTION_KEY);