Problem Statement:
I'm trying to integrate API which AES/CBC/PKCS5 Padding. After some research I found the implementation on following article.
However, In this article there were using mcrypt which is deprecated and removed from PHP 7.2. Hence, I'm looking to modify above implementation in openssl.
There is function pkcs5_pad for PKCS5 padding the data which require parameter as data and blocksize. And there are no alternative to mcrypt_get_block_size in openssl.
Code Snippet
pkcs5_pad & pkcs5_unpad
function pkcs5_pad ($text, $blocksize)
{
$pad = $blocksize - (strlen($text) % $blocksize);
return $text . str_repeat(chr($pad), $pad);
}
function pkcs5_unpad($text)
{
$pad = ord($text{strlen($text)-1});
if ($pad > strlen($text)) return false;
if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) return false;
return substr($text, 0, -1 * $pad);
}
Trying to convert following
$paddedData = pkcs5_pad(
$data,
mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC)
);
$encrypteddata = mcrypt_encrypt(
MCRYPT_RIJNDAEL_128,
hex2bin(md5($key)),
$paddedData,
MCRYPT_MODE_CBC,
$iv
);
TO
$paddedData = pkcs5_pad($data); // How do I getBlock size in OpenSSL. i.e. Alternate to mcrypt_get_block_size
$encrypteddata = openssl_encrypt(
$paddedData,
$cipher,
$key,
$options=OPENSSL_RAW_DATA,
$iv
);
Trial & Error:
I found some file after some research in Github. But didn't know how to use this file to convert data into pkcs5 padded data.
The good news is - OpenSSL has a "built in" padding so you don't have to worry about it.
The full running code below shows you how to encrypt or decrypt a string using a 32 bytes long, randomly generated key for AES-256. The AES mode is CBC, and it is using the PKCS5/7 padding. The output of the encryption is Base64 encoded (usefull for transport via Email), of course you can leave the Base64 en-/decoding out when saving the ciphertext to a file and later read the file for decryption.
Please be aware that there are is no exception handling and the code is for educational purpose:
The output looks like: