In cryptography, PKCS7 padding is used to ensure the confidentiality of sensitive data by adding additional bytes to the end of a message. This padding allows for the encrypted data to be a multiple of the block size of the encryption algorithm being used, typically AES (Advanced Encryption Standard) in 128-bit mode.
PKCS7 padding follows a specific algorithm:
To add PKCS7 padding, you can follow these steps:
import base64 from Crypto.Cipher import AES from Crypto.Util.Padding import pad # Sample data to encrypt data = "Hello, World!" # Define the AES key (128 bits = 16 bytes) key = 'YOUR_AES_KEY_16_BYTES_LONG' # Initialization vector (IV) for ECB mode is not used and ignored iv = '0' * 16 # Create an AES cipher in ECB mode cipher = AES.new(key, AES.MODE_ECB) # Pad the data before encryption padded_data = pad(data, 16) # 16 is the block size for AES-128 # Encrypt the padded data ciphertext = cipher.encrypt(padded_data) # Encode the ciphertext in base64 for transmission ciphertext_base64 = base64.b64encode(ciphertext).decode('utf-8') # Print the encrypted and base64-encoded ciphertext print(ciphertext_base64)
To remove PKCS7 padding, you can follow these steps:
import base64 from Crypto.Cipher import AES from Crypto.Util.Padding import unpad # Sample base64-encoded ciphertext to decrypt ciphertext_base64 = 'ENCRYPTED_AND_BASE64_ENCODED_DATA' # Decode the base64 ciphertext ciphertext = base64.b64decode(ciphertext_base64) # Define the AES key (128 bits = 16 bytes) key = 'YOUR_AES_KEY_16_BYTES_LONG' # Initialization vector (IV) for ECB mode is not used and ignored iv = '0' * 16 # Create an AES cipher in ECB mode cipher = AES.new(key, AES.MODE_ECB) # Decrypt the ciphertext decrypted = cipher.decrypt(ciphertext) # Remove the padding from the decrypted data data = unpad(decrypted, 16) # Print the decrypted and unpadded data print(data.decode('utf-8'))
The above is the detailed content of How to Add and Remove PKCS7 Padding from AES-Encrypted Strings?. For more information, please follow other related articles on the PHP Chinese website!