Home >Backend Development >PHP Tutorial >How to Add and Remove PKCS7 Padding for AES Encryption in ECB Mode?
Adding and Removing PKCS7 Padding for AES Encryption
When encrypting data using 128-bit AES encryption in Electronic Codebook (ECB) mode, it's necessary to add and remove PKCS7 padding to the plaintext and ciphertext, respectively.
PKCS7 padding is a method defined in RFC 5652 that ensures the data length is a multiple of the block size. It involves appending as many bytes as needed to fill the last block, where each byte is set to the number of padding bytes added.
Adding PKCS7 Padding
To add PKCS7 padding to plaintext before encryption using AES:
Removing PKCS7 Padding
To remove PKCS7 padding from ciphertext after decryption using AES:
PHP functions to perform these operations:
function encrypt($plaintext, $key) { $block = mcrypt_get_block_size('aes', 'ecb'); $pad = $block - (strlen($plaintext) % $block); $plaintext .= str_repeat(chr($pad), $pad); return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $plaintext, MCRYPT_MODE_ECB); } function decrypt($ciphertext, $key) { $ciphertext = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $ciphertext, MCRYPT_MODE_ECB); $block = mcrypt_get_block_size('aes', 'ecb'); $pad = ord($ciphertext[strlen($ciphertext) - 1]); return substr($ciphertext, 0, -1 * $pad); }
Note that it's recommended to use CBC or other chaining modes instead of ECB for secure encryption.
The above is the detailed content of How to Add and Remove PKCS7 Padding for AES Encryption in ECB Mode?. For more information, please follow other related articles on the PHP Chinese website!