在密碼學中,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)
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中文網其他相關文章!