1

我可以使用来自特定文件的密钥进行加密key1,但我无法使用相同的密钥解密文件,cryptography.fernet.InvalidToken即使它是来自同一文件的相同密钥Securi1.key并读取为rb

# This function calls the pre-existing key to encrypt and decrypt files
def securi1_key():
    file = open("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Keys/Securi1.key", 'rb')
    global key1
    key1 = file.read()
    file.close()

# this code encrypts the documents text and then replaces the raw text with encrypted string
def rewrite_yellow():
    securi1_key()
    save_yellow_text() #existing text
    #   get key from file
    file = open("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Keys/Securi1.key", 'rb')
    texty = scan4yellow.decode("utf-8")
    encodedy = texty.encode()

    #   encrypt message
    f = Fernet(key1)
    encryptedy = f.encrypt(encodedy)
    # replaces document text with encrypted text
    document = docx.Document(f1)
    for paragraph in document.paragraphs:
        if scan4yellow.decode("utf-8") in paragraph.text:
            inline = paragraph.runs
            # loops for runs
            for i in range(len(inline)):
                if scan4yellow.decode("utf-8") in inline[i].text:
                    text = inline[i].text.replace(scan4yellow.decode("utf-8"), encryptedy.decode("utf-8"))
                    inline[i].text = text
    document.save(f1)

#this function should ideally decrypt
def decrypt_yellow():
    securi1_key()
    inputfile = (f1)
    list_of_inputfiles = os.listdir("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Text/")

    with open(inputfile, "rb") as f:
        data = f.read()

    file = open("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Keys/Securi1.key", "rb")
    global key1
    key1 = file.read()
    file.close()

    f2 = Fernet(key1) # <-- key1 is from Securi1 so it should decrypt
    decryptedy = decryptedy = f2.decrypt(data) #encrypted contains OG text so it decrypts it with the key
    # replaces the text
    document = docx.Document(f1)
    for paragraph in document.paragraphs:
        if scan4yellow.decode("utf-8") in paragraph.text:
            inline = paragraph.runs
            #loops for the runs
            for i in range(len(inline)):
                if scan4yellow.decode("utf-8") in inline[i].text:
                    text = inline[i].text.replace(scan4yellow.decode("utf-8"), decryptedy.decode("utf-8"))
                    inline[i].text = text
    document.save(f1)
    inputfile.close()
    os.remove(inputfile)

它应该解密文本,然后用加密文件中不会解密的OG文本替换加密文本

4

0 回答 0