Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save waltzie/295fb2473f3773965d050b86482e0449 to your computer and use it in GitHub Desktop.
Save waltzie/295fb2473f3773965d050b86482e0449 to your computer and use it in GitHub Desktop.
php AES-128-CBC mcrypt & openssl
<?php
function encrypt_mcrypt($msg, $key, $iv = null) {
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
if (!$iv) {
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
}
$pad = $iv_size - (strlen($msg) % $iv_size);
$msg .= str_repeat(chr($pad), $pad);
$encryptedMessage = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $msg, MCRYPT_MODE_CBC, $iv);
return base64_encode($iv . $encryptedMessage);
}
function decrypt_mcrypt($payload, $key) {
$raw = base64_decode($payload);
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = substr($raw, 0, $iv_size);
$data = substr($raw, $iv_size);
$result = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv);
$ctrlchar = substr($result, -1);
$ord = ord($ctrlchar);
if ($ord < $iv_size && substr($result, -ord($ctrlchar)) === str_repeat($ctrlchar, $ord)) {
$result = substr($result, 0, -ord($ctrlchar));
}
return $result;
}
function encrypt_openssl($msg, $key, $iv = null) {
$iv_size = openssl_cipher_iv_length('AES-128-CBC');
if (!$iv) {
$iv = openssl_random_pseudo_bytes($iv_size);
}
$encryptedMessage = openssl_encrypt($msg, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
return base64_encode($iv . $encryptedMessage);
}
function decrypt_openssl($payload, $key) {
$raw = base64_decode($payload);
$iv_size = openssl_cipher_iv_length('AES-128-CBC');
$iv = substr($raw, 0, $iv_size);
$data = substr($raw, $iv_size);
return openssl_decrypt($data, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
}
@waltzie
Copy link
Author

waltzie commented Feb 5, 2019

Why mixing them does not work?

$data = "Hello World!";
$key = hash('sha256',"secret",true);

$enc = encrypt_openssl($data,$key);
echo "\nencrypted: $enc";
$dec = decrypt_mcrypt($enc,$key);
echo "\ndecrypted: $dec";

$enc = encrypt_mcrypt($data,$key);
echo "\nencrypted: $enc";
$dec = decrypt_openssl($enc,$key);
echo "\ndecrypted: $dec";

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment