我正在使用AES对象(aesDecryptObj)解密使用单独的AES对象(aesEncryptObj)加密的密文。
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会产生成功的结果,但是,当我连续两次使用aesDecryptObj解密给定的密文时,会收到以下错误:
File "/usr/lib64/python3.6/site-packages/Cryptodome/Util/Padding.py", line 90, in unpad
raise ValueError("Padding is incorrect.")
ValueError: Padding is incorrect.
在相同的密文下,aesDecryptObj是否会产生与首次解密该值相同的结果?
答案 0 :(得分:1)
AES对象具有状态(至少使用AES.MODE_CBC
)。您可以使用iv=<My Init Vector>
初始化该状态。当您解密密文时,状态会改变。您需要重新初始化对象,然后再次调用解密。
您可能想要类似的东西:
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()
。