1

I'm writing a simple encryption/encoding program using base64 and fernet, but when decrypting fernet keeps raising an Invalid Token error. Here is the code:

from cryptography.fernet import Fernet import base64 as b64,random as rd def encryt(data): key=Fernet.generate_key() data=bytes(data,"utf-8") key2=rd.randint(0,5) for i in range(key2): data=b64.a85encode(data) data=b64.b32hexencode(data) fernet=Fernet(key) encrypted=fernet.encrypt(data) for i in range(key2): encrypted=b64.b32hexencode(encrypted) encrypted=b64.a85encode(encrypted) for i in range(key2): key=b64.b64encode(key) key=b64.a85encode(key) key=b64.b32hexencode(key) final=b64.b85encode(bytes(str(key2),"utf-8")).decode()+"/?\\"+encrypted.decode()+"~`~"+key.decode() return(final) def decrypt(data): a=data.split("/?\\") key2=int(b64.b85decode(bytes(a[0],"utf-8"))) b=a[1].split("~`~") encrypted=bytes(b[0],"utf-8") key=bytes(b[1],"utf-8") for i in range(key2): key=b64.b32hexdecode(key) key=b64.a85decode(key) key=b64.b64decode(key) fernet=Fernet(key) decrypted=fernet.decrypt(encrypted) for i in range(key2): decrypted=b64.a85decode(decrypted) decrypted=b64.b32hexdecode(decrypted) return(decrypted.decode()) q="testtes:1234//te" w=encryt(q) print(w) print(decrypt(w)) 

Hope you guys know how to fix this!

I'm getting

Traceback (most recent call last): File "c:\Users\teech\projects\Wethgan\pyencrypter.py", line 40, in <module> print(decrypt(w)) ^^^^^^^^^^ File "c:\Users\teech\projects\Wethgan\pyencrypter.py", line 32, in decrypt decrypted=fernet.decrypt(encrypted) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Python312\Lib\site-packages\cryptography\fernet.py", line 84, in decrypt timestamp, data = Fernet._get_unverified_token_data(token) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Python312\Lib\site-packages\cryptography\fernet.py", line 118, in _get_unverified_token_data raise InvalidToken cryptography.fernet.InvalidToken 

most of the time, but sometimes it just suddenly works.

2
  • In decrypt(), all operations regarding decoding and decryption must be performed in reverse order to encryption. This is not the case in your code: Firstly, the decoding of the ciphertext is missing (which you can easily recognize by the fact that there are three for loops in encrypt() but only two in decrypt()). Secondly, there is a bug in the order in which the decrypted data is decoded. If both are fixed, decryption works. Commented Jul 1, 2024 at 6:54
  • Note that the concatenation of the Fernet key with the ciphertext makes your encryption completely insecure and that multiple binary-to-text encodings do not increase security, but are only inefficient. Commented Jul 2, 2024 at 7:12

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.