0

I am making a simple flask api which is encoding and decoding the coming string. I have no problem with encoding but I am getting InvalidToken error when decoding. I tried smth. but could not make it. Code:

from flask import Flask,jsonify,request
from cryptography.fernet import Fernet

app = Flask(__name__)
key = Fernet.generate_key()
fernet = Fernet(key)
@app.route('/decode',methods = ["POST"])
def decode():
    response = {'encoded_text': request.json['encoded_text']}
    text = response['encoded_text']
    print(text)
    decryptedbytes = fernet.decrypt(text)
    decryptedstr = decryptedbytes.decode('utf-8')
    return decryptedstr


if __name__ == '__main__':
    app.run(debug=True)

Giving: TypeError: token must be bytes.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
aoiTenshi
  • 547
  • 1
  • 6
  • 20

1 Answers1

0

You're passing fernet.decrypt an str instead of a bytes object.

How is your encrypted data encoded within the JSON? The usual is a base64:

import base64
decryptedbytes = fernet.decrypt(base64.b64decode(text))

Keep in mind JSON does not support arbitrary bytes.

As a side note, generating a key for the fernet algorithm every time the program starts, means that if your server restarts, all of the data is gone.

Bharel
  • 23,672
  • 5
  • 40
  • 80
  • So, I should make my own key and send it to server too, right? – aoiTenshi May 20 '22 at 12:26
  • @aoiTenshi Exactly. Either a static one on the server for encrypting/decrypting only what was sent through the server, or one passed by the client for custom encrypt/decrypt operations. As for storing it static, use environment variables or other "secret" solutions, not plaintext in the server code. – Bharel May 20 '22 at 12:33