Python加密库解密使用相同变量产生InvalidTag错误

2024-10-03 06:19:27 发布

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

我正在尝试为一个安全的云共享应用程序项目创建一个高级加密和解密类。为了使用相同的密钥、nonce和“已授权但未加密的数据”,我不知道这意味着什么;我使用这个类。但是,我不明白为什么我得到InvalidTag异常。我正在恢复相同的值并对称地进行解密。有趣的是,它没有在变量中存储值的类。用相同的值恢复相同的变量有什么区别?你知道吗

import os
from base64 import urlsafe_b64encode, urlsafe_b64decode
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

class cryptoUtils(AESGCM):
    def __init__(self, key=None):
        self.key = key if key else self.newKey()
        self.nonce = os.urandom(12)
        # Initialize AESGCM
        super().__init__(self.key) <------------------

    def encryptFile(self, fileName):
        with open(fileName, "rb") as aFile:
            pText = aFile.read()
        eText = self.encrypt(self.nonce, pText, None)
        newFile = "{}.enc".format(fileName)
        with open(newFile, "wb") as bFile:
            bFile.write(eText)

    def decryptFile(self, fileName):
        with open(fileName, "rb") as bFile:
            eText = bFile.read()
        pText = self.decrypt(self.nonce, eText, None)
        newFile = fileName[0:-4]
        with open(newFile, "wb") as aFile:
            aFile.write(pText)

    def exportKey(self):
        key = "".join(map(chr, self.key))
        nonce = "".join(map(chr, self.nonce))
        str = "{}:{}".format(key, nonce)
        return str

    def importKey(self, input):
        self.key = input.split(":")[0]
        self.nonce = input.split(":")[1] 

我在主文件中导入这个类并像这样使用它:

from crypto import cryptoUtils

if __name__ == "__main__":
    cu1 = cryptoUtils()
    cu1.importKey("Gr0k6-ve8p7_5ysGEoLmnQ==:LylEffLP1a_fElsy")
    cu1.encryptFile("T.pdf")

    cu2 = cryptoUtils()
    cu2.importKey("Gr0k6-ve8p7_5ysGEoLmnQ==:LylEffLP1a_fElsy")
    cu2.decryptFile("T.pdf.enc")

谢谢。你知道吗


Tags: keyimportselfdefaswithopenfilename
1条回答
网友
1楼 · 发布于 2024-10-03 06:19:27

导入密钥后,您忘记调用super().__init__(self.key)。键已设置,但很可能从未直接使用新的键值。你知道吗

请不要扩展类,比如AESGCM。相反,使用这样的类编写一个类来执行所需的功能。然后围绕特定功能编写测试用例,在本例中是加密/解密特定文件。你知道吗

相关问题 更多 >