gpt4 book ai didi

python - AES 加密存在问题。无法用正确的 key 解密

转载 作者:行者123 更新时间:2023-12-01 01:14:52 26 4
gpt4 key购买 nike

我正在尝试解密加密数据。使用 pycryptodome lib 以 AES CBC 模式对数据进行加密。出现这样的错误——“ValueError:不正确的 AES key 长度(256 字节)

import os
from Crypto import Random
from Crypto.Cipher import AES

class AESCipher:
def __init__(self, key):
pass

def pad(self, s):
return s + b"\0" * (AES.block_size - len(s) % AES.block_size)

def encrypt(self, message, key, key_size=256):
message = self.pad(message)
iv = Random.new().read(AES.block_size)
cipher = AES.new(key, AES.MODE_CBC, iv)
return iv + cipher.encrypt(message)

def decrypt(self, ciphertext, key):
iv = ciphertext[:AES.block_size]
cipher = AES.new(key, AES.MODE_CBC, iv)
plaintext = cipher.decrypt(ciphertext[AES.block_size:])
return plaintext.rstrip(b"\0")

def send_data(data)
key = os.urandom(16)
cipher = AESCipher(key)
ciphertext = cipher.encrypt(data, key)
return key, ciphertext

def receive_data(key, data):
cipher = AESCipher(key)
decrypted = cipher.decrypt(data, key)
return decrypted

data = b'12 43 42 46 af'
key, ciphertext = send_data(data)
decrypted = receive_data(key, data)

最佳答案

我认为你要解密的是密文,而不是原始数据(未加密):

decrypted = receive_data(key, ciphertext)

关于python - AES 加密存在问题。无法用正确的 key 解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54450159/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com