I inherited a project that was coded back in the PHP 5.X days. The site is running on PHP 7.1 right now and using the MCRYPT library for it's encryption and decryption functions.
I need to upgrade to PHP 7.2, which means bye bye MCRYPT!
Not being familiar with encryption is causing issues with trying to convert to OPENSSL
Below is the code that is currently in place.
function decrypt($encryptedText)
{
$key = pack('H*', 'NOTHINGTOSEEHERE');
$enc = base64_decode($encryptedText);
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $enc, MCRYPT_MODE_ECB, $key), "\x80");
}
function encrypt($plaintext)
{
$key = pack('H*', 'NOTHINGTOSEEHERE');
$blockSize = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
$inputLength = strlen($plaintext);
$blockCount = floor($inputLength / $blockSize);
$padding = ($blockCount + 1) * $blockSize - $inputLength;
$paddedPlainText = str_pad($plaintext, $inputLength + $padding, "\x80", STR_PAD_RIGHT);
$enc = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $paddedPlainText, MCRYPT_MODE_ECB, $key);
return base64_encode($enc);
}
I have looked over several other StackOverflow posts that go over this exact topic of converting from MCRYPT to OPENSSL, and based on everything I have read, I came up with the following code, which doesn't work.
function decrypt($encryptedText)
{
$key = pack('H*', 'NOTHINGTOSEEHERE');
$ivsize = openssl_cipher_iv_length('AES-128-ECB');
$iv = openssl_random_pseudo_bytes($ivsize);
$enc = base64_decode($encryptedText);
return trim(openssl_decrypt($enc, 'AES-128-ECB', $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv);
}
function encrypt($plaintext)
{
$key = pack('H*', 'NOTHINGTOSEEHERE');
$ivsize = openssl_cipher_iv_length('AES-128-ECB');
$iv = openssl_random_pseudo_bytes($ivsize);
$enc = openssl_encrypt($plaintext, 'AES-128-ECB', $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv);
return base64_encode($enc);
}
I am not sure, but I have a feeling the issue has to do with the padding of the text in the old encryption function this is causing the new code not to work. I don't know how to integrate that into the OPENSSL functions, if that is indeed the problem.
$blockSize = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
$inputLength = strlen($plaintext);
$blockCount = floor($inputLength / $blockSize);
$padding = ($blockCount + 1) * $blockSize - $inputLength;
$paddedPlainText = str_pad($plaintext, $inputLength + $padding, "\x80", STR_PAD_RIGHT);
Again, not being familiar with encryption, any/all help is appreciated so I can figure out and understand what I am doing wrong.