无法使用同一AES对象对给定的cyphertext解密两次

2024-10-03 11:21:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用AES对象(AESEcryptobj)来解密使用单独AES对象(AESEcryptobj)加密的cyphertext。你知道吗

def aesInit():
    global aesEncryptObj
    global aesDecryptObj
    aesKey = <my key>
    aesEncryptObj = AES.new(aesKey, AES.MODE_CBC, iv=<My Init Vector>)
    aesDecryptObj = AES.new(aesKey, AES.MODE_CBC, iv=<My Init Vector>)

def aesEncrypt(clearStr):
    global aesEncryptObj 
    padded_data = pad(str(clearStr).encode("utf-8"), aesEncryptObj.block_size)
    e = aesEncryptObj.encrypt(padded_data)
    eb64 = base64.b64encode(e)
    d = eb64.decode('ascii')
    return(d)

def aesDecrypt(encryptedStr):
    global aesDecryptObj
    e = base64.b64decode(encryptedStr)
    b = aesDecryptObj.decrypt(e)
    b = unpad(b, aesDecryptObj.block_size)
    clearStr = b.decode('utf-8')
    return(clearStr)

aesInit()

cypherText = aesEncrypt('test') #this line will render the same result no matter how many times it is repeated

print(aesDecrypt(cypherText)) #this line executes fine
print(aesDecrypt(cypherText)) #this line throws the "padding is incorrect" error

按顺序使用aesEncryptObj任意次数都会产生成功的结果,但是,当我使用aesEncryptObj连续两次或多次解密给定的密码文本时,我会收到以下错误:

File "/usr/lib64/python3.6/site-packages/Cryptodome/Util/Padding.py", line 90, in unpad
    raise ValueError("Padding is incorrect.")
ValueError: Padding is incorrect.

如果给定相同的密文,AESEcryptobj是否应该产生与第一次解密值时相同的结果?你知道吗


Tags: isdeflinethisglobalaespaddingincorrect
1条回答
网友
1楼 · 发布于 2024-10-03 11:21:41

AES对象有一个状态(至少有AES.MODE_CBC)。用iv=<My Init Vector>初始化该状态。当你解密密文时,状态会改变。在再次调用decrypt之前,需要重新初始化对象。你知道吗

你可能想要这样的东西:

def aesDecrypt(encryptedStr):
    aesKey = <my key>
    aesDecryptObj = AES.new(aesKey, AES.MODE_CBC, iv=<My Init Vector>)
    e = base64.b64decode(encryptedStr)
    b = aesDecryptObj.decrypt(e)
    b = unpad(b, aesDecryptObj.block_size)
    clearStr = b.decode('utf-8')
    return(clearStr)

或者,在解密第一个密文之后,您可以简单地再次调用aesInit()。你知道吗

相关问题 更多 >