MisterGod
MisterGod

Reputation: 25

InvalidToken with python cryptography module

I have this error =>cryptography.fernet.InvalidToken, when I try to decrypt the content of my file at this line exit1 = key.decrypt(listCipher[0]). I sought everywhere but I didn't found anything about this problem. I tried to replace the list by using ConfigParser but it still doesn't work and I don't think that is the problem. Some help is welcome.

from cryptography.fernet import Fernet

entry1 = "First_sentence"
entry2 = "Second_sentence"
entry3 = "Third_sentence"

    ##--- Key creation
firstKey = Fernet.generate_key()
file = open('.\\TEST\\key.key', 'wb') 
file.write(firstKey)
file.close()

    ##--- Cipher entries
key = Fernet(firstKey)
chiffrentry1 = key.encrypt(bytes(entry1, "utf-8"))
chiffrentry2 = key.encrypt(bytes(entry2, "utf-8"))
chiffrentry3 = key.encrypt(bytes(entry3, "utf-8"))
listAll = [chiffrentry1, chiffrentry2, chiffrentry3]

    ##-- Write cipher text in file
with open('.\\TEST\\text_encrypt.txt', 'w') as pt:
    for ligne in listAll:
        pt.write("%s\n" % ligne)

    ##--- Recover file to decrypt cipher text
listCipher = []

with open('.\\TEST\\text_encrypt.txt', 'rb') as pt:
    for line in pt:
        listCipher.append(line.strip())

exit1 = key.decrypt(listCipher[0])
exit2 = key.decrypt(listCipher[1])
exit3 = key.decrypt(listCipher[2])

print(exit1)
print(exit2)
print(exit3)

Upvotes: 2

Views: 3007

Answers (1)

C.Nivs
C.Nivs

Reputation: 13106

The '%s\n'%ligne is modifying your data. For instance if I do the following:

>>> with open('afile.txt', 'w') as fh:
     for i in range(2):
             fh.write('%s\n'%b'hi there')

12
12
>>> with open('afile.txt', 'rb') as fh:
     for line in fh:
             print(line)

b"b'hi there'\n"
b"b'hi there'\n"

The issue here is the type conversions you are doing. Fernet's operations expect bytes and you are storing the encrypted values as strings. When you convert a bytes object to a string, you don't get exactly what that byte-string was. To avoid this, don't convert the types

with open('.\\TEST\\text_encrypt.txt', 'wb') as pt:
    # join supports byte-strings
    to_write = b'\n'.join(listAll)
    pt.write(to_write)

# Now I can read a bytes object directly
with open('.\\TEST\\text_encrypt.txt', 'rb') as fh:
    # this is a single bytes-string with b'\n' chars inside it
    contents = fh.read()

# byte-strings also support split
ciphers = contents.split(b'\n')

for cipher in ciphers:
    print(key.decrypt(cipher))

Upvotes: 1

Related Questions