Skip to main content
 首页 » 编程设计

python之无法使用相同的 AES 对象两次解密给定的密文

2024年11月24日7arxive

我正在使用 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 是否会产生与第一次解密该值时相同的结果?

请您参考如下方法:

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()再次解密第一个密文。