在密码学中,PKCS7 填充用于通过向字符串添加额外字节来确保敏感数据的机密性。消息结束。此填充允许加密数据是所使用的加密算法的块大小的倍数,通常是 128 位模式下的 AES(高级加密标准)。
PKCS7 填充遵循特定算法:
要添加 PKCS7 填充,您可以按照以下操作步骤:
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)
要删除 PKCS7 填充,您可以按照以下步骤操作:
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'))
以上是如何在 AES 加密字符串中添加和删除 PKCS7 填充?的详细内容。更多信息请关注PHP中文网其他相关文章!