TopUser
TopUser

Reputation: 72

Bytes encoding in cryptography module giving error

I am using the cryptography module's Fernet for encoding.
The Fernet technique converts the data to bytes using a key, and then we can convert the bytes back to a string using that same key.
I want to convert the encoded bytes to a string and store that string. (It is important for me to convert it to a string).

So, I used the following way:

f = Fernet(key)
mystr = str(f.encrypt(bytes(mystr, "utf-8")))        # convert mystr to bytes

But now, when I try to convert the string back to bytes, I am unable to decrypt it again.

mystr = str(f.decrypt(bytes(mystr, "utf-8")))        # convert mystr back to a string

I get the following error:

  File "C:\Users\Me\Desktop\Python\Encode.py", line 155, in encode
    data = str(f.decrypt(bytes(data, "utf-8")))
  File "C:\Users\Me\AppData\Local\Programs\Python\Python39\lib\site-packages\cryptography\fernet.py", line 75, in decrypt
    timestamp, data = Fernet._get_unverified_token_data(token)
  File "C:\Users\Me\AppData\Local\Programs\Python\Python39\lib\site-packages\cryptography\fernet.py", line 107, in _get_unverified_token_data
    raise InvalidToken
cryptography.fernet.InvalidToken

I tried decrypting like:

mystr = str(f.decrypt(bytes(mystr, "ascii")))

or

mystr = str(f.decrypt(bytes(mystr, "base64")))

but, the error is still present.

Upvotes: 1

Views: 784

Answers (1)

furas
furas

Reputation: 142939

You should use print() to see what you have in variables after using bytes and `str()

When you use

 bytes('abc', 'utf-8')

then you get

 b'abc'

and when you use

 str(b'abc')

then you get

 "b'abc'"

instead of 'abc' - and this prefix b and ' ' change everything. Now you have string with 6 chars instead of 3 chars.

You should use encode to create bytes and decode to create string again

  'abc'.encode('utf-8').decode('utf-8')

Upvotes: 2

Related Questions