使用相同的密钥解密文本会得到无效的令牌

时间:2019-05-30 03:54:19

标签: python encryption cryptography python-cryptography

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

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)```

It should decrypt the text and then replace the encrypted text with the OG text which is in the encrypted file which wont decrypt

0 个答案:

没有答案