Home >Backend Development >PHP Tutorial >How to Add and Remove PKCS7 Padding for AES Encryption in ECB Mode?

How to Add and Remove PKCS7 Padding for AES Encryption in ECB Mode?

Barbara Streisand
Barbara StreisandOriginal
2024-12-03 22:57:20681browse

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:

  1. Determine the block size of the AES algorithm (usually 16 bytes for 128-bit AES).
  2. Calculate the number of bytes needed to fill the last block: pad = block_size - (plaintext_length % block_size).
  3. Create a string with the repeated character chr(pad) to represent the padding bytes.
  4. Append the padding string to the plaintext.

Removing PKCS7 Padding

To remove PKCS7 padding from ciphertext after decryption using AES:

  1. Determine the block size of the AES algorithm.
  2. Get the last byte of the ciphertext.
  3. Set the padding size pad equal to the value of the last byte.
  4. Cut off the last pad bytes from the ciphertext.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn