ValueError:Python 中数据掩码中的 AES 密钥长度(4 字节)不正确

ValueError: Incorrect AES key length (4 bytes) in data masking in Python

提问人:sourabh dani 提问时间:2/23/2023 更新时间:2/23/2023 访问量:42

问:

在上面的程序中,我收到值错误,提示 AES 密钥长度不正确(4 字节)。如果我只是执行密码 = AES.new(key, AES.MODE_CBC, iv) 在函数之外,它返回值。

import hashlib
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad

# Define sensitive data
sensitive_data = {
    'name': 'John Doe',
    'email': '[email protected]',
    'phone': '555-1234'
}

# Define encryption key
key = hashlib.sha256(b"mysecretkey").digest()

# Define initialization vector
iv = b"1234567890123456"

# Define encryption function
def encrypt_data(data, key, iv):
    cipher = AES.new(key, AES.MODE_CBC, iv)
    plaintext = str(data).encode('utf-8')
    padded_plaintext = pad(plaintext, AES.block_size)
    ciphertext = cipher.encrypt(padded_plaintext)
    return ciphertext

# Define decryption function
def decrypt_data(data, key, iv):
    cipher = AES.new(key, AES.MODE_CBC, iv)
    padded_plaintext = cipher.decrypt(data)
    plaintext = unpad(padded_plaintext, AES.block_size)
    return plaintext.decode('utf-8')

# Mask sensitive data
def mask_data(data, key, iv):
    masked_data = {}
    for key, value in data.items():
        masked_data[key] = encrypt_data(value, key, iv)
    return masked_data

# Unmask sensitive data
# def unmask_data(data, key, iv):
    unmasked_data = {}
    for key, value in data.items():
        unmasked_data[key] = decrypt_data(value, key, iv)
    return unmasked_data

# Print original and masked data
print('Original Data:')
print(sensitive_data)

masked_data = mask_data(sensitive_data, key, iv)
print('Masked Data:')
print(masked_data)

unmasked_data = unmask_data(masked_data, key, iv)
print('Unmasked Data:')
print(unmasked_data)

在上面的程序中,我收到值错误,提示 AES 密钥长度不正确(4 字节)。如果我只是执行密码 = AES.new(key, AES.MODE_CBC, iv) 在函数之外,它返回值。

Python Caesar-Cipher 数据掩码

评论


答: 暂无答案