Skip to content
Advertisement

AES/CBC/PKCS5 Padding | Alternate to mcrypt_get_block_size() in Php OpenSSL

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

JavaScript

Trying to convert following

JavaScript

TO

JavaScript

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.


Advertisement

Answer

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:

JavaScript

The output looks like:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement