PKCS7 Padding for AES Encryption
When encrypting data using 128-bit AES encryption in ECB mode, PKCS7 padding may be necessary to ensure the data is a multiple of the block size. This padding adds a variable number of bytes to the end of the data, where the value of each byte represents the number of padding bytes added.
Adding PKCS7 Padding
To add PKCS7 padding to a plaintext string:
Example in PHP (Mcrypt)
<?php $block_size = mcrypt_get_block_size('rijndael_128', 'ecb'); // Block size for AES $padding_size = $block_size - (strlen($plaintext) % $block_size); $plaintext .= str_repeat(chr($padding_size), $padding_size); ?>
Removing PKCS7 Padding
To remove PKCS7 padding from a ciphertext string:
Example in PHP (Mcrypt)
<?php $ciphertext = ...; // Encrypted ciphertext with PKCS7 padding $key = ...; // Encryption key $decrypted_plaintext = mcrypt_decrypt('rijndael_128', $key, $ciphertext, 'ecb'); $padding_length = ord($decrypted_plaintext[strlen($decrypted_plaintext) - 1]); if (str_repeat(chr($padding_length), $padding_length) === substr($decrypted_plaintext, -1 * $padding_length)) { $plaintext = substr($decrypted_plaintext, 0, -1 * $padding_length); // Remove padding } else { // Invalid padding } ?>
The above is the detailed content of How Does PKCS7 Padding Work with AES Encryption?. For more information, please follow other related articles on the PHP Chinese website!