krot

MCrypt, Rijndael-256, and CBC

Jul 30th, 2016
90
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2. //https://www.warpconduit.net/2013/04/14/highly-secure-data-encryption-decryption-made-easy-with-php-mcrypt-rijndael-256-and-cbc/#more-626
  3. // Define a 32-byte (64 character) hexadecimal encryption key
  4. // Note: The same encryption key used to encrypt the data must be used to decrypt the data
  5. define('ENCRYPTION_KEY', 'd0a7e7997b6d5fcd55f4b5c32611b87cd923e88837b63bf2941ef819dc8ca282');
  6. // Encrypt Function
  7. function mc_encrypt($encrypt, $key){
  8.     $encrypt = serialize($encrypt);
  9.     $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC), MCRYPT_DEV_URANDOM);
  10.     $key = pack('H*', $key);
  11.     $mac = hash_hmac('sha256', $encrypt, substr(bin2hex($key), -32));
  12.     $passcrypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $encrypt.$mac, MCRYPT_MODE_CBC, $iv);
  13.     $encoded = base64_encode($passcrypt).'|'.base64_encode($iv);
  14.     return $encoded;
  15. }
  16. // Decrypt Function
  17. function mc_decrypt($decrypt, $key){
  18.     $decrypt = explode('|', $decrypt.'|');
  19.     $decoded = base64_decode($decrypt[0]);
  20.     $iv = base64_decode($decrypt[1]);
  21.     if(strlen($iv)!==mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC)){ return false; }
  22.     $key = pack('H*', $key);
  23.     $decrypted = trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $decoded, MCRYPT_MODE_CBC, $iv));
  24.     $mac = substr($decrypted, -64);
  25.     $decrypted = substr($decrypted, 0, -64);
  26.     $calcmac = hash_hmac('sha256', $decrypted, substr(bin2hex($key), -32));
  27.     if($calcmac!==$mac){ return false; }
  28.     $decrypted = unserialize($decrypted);
  29.     return $decrypted;
  30. }
  31. echo '<h1>Rijndael 256-bit CBC Encryption Function</h1>';
  32. $data = 'Super secret confidential string data.';
  33. $encrypted_data = mc_encrypt($data, ENCRYPTION_KEY);
  34. echo '<h2>Example #1: String Data</h2>';
  35. echo 'Data to be Encrypted: ' . $data . '<br/>';
  36. echo 'Encrypted Data: ' . $encrypted_data . '<br/>';
  37. echo 'Decrypted Data: ' . mc_decrypt($encrypted_data, ENCRYPTION_KEY) . '</br>';
  38. $data = array(1, 5, 8, 9, 22, 10, 61);
  39. $encrypted_data = mc_encrypt($data, ENCRYPTION_KEY);
  40. echo '<h2>Example #2: Non-String Data</h2>';
  41. echo 'Data to be Encrypted: <pre>';
  42. print_r($data);
  43. echo '</pre><br/>';
  44. echo 'Encrypted Data: ' . $encrypted_data . '<br/>';
  45. echo 'Decrypted Data: <pre>';
  46. print_r(mc_decrypt($encrypted_data, ENCRYPTION_KEY));
  47. echo '</pre>';
  48. ?>
RAW Paste Data