FERNET Error : cryptography.fernet.InvalidToken

509 Views Asked by At

I'm using python Fernet library because I need to encrypt and store a password in the db, then I need to query the encrypted password and decrypt it to pass it into a variable, this is an FTP password the application needs to do some stuff. Since I just need to store the password ones in the db, I run the encryption code ones to store it in the db. Then I comment the code and use the function decrypt_pwd I created to decrypt it, but returns erroro Invalid Token. ANy idea? Please edit my code in case.

This is the store_user_db.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from cryptography.fernet import Fernet

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///data-users2.sqlite"
db = SQLAlchemy(app)

key = Fernet.generate_key()
f = Fernet(key)

class User(db.Model):
    #CREATE THE TABLE; DEFINE COLUMNS; ENCRYPT PWD
    __tablename__ = "user"
    id = db.Column(db.Integer(), primary_key=True, autoincrement=True)
    username = db.Column(db.String(64), unique=True)
    pwd = db.Column(db.LargeBinary(), unique=True)

    def __init__(self, id, username, pwd):
        token = f.encrypt(pwd)
        self.id = id
        self.username = username
        self.pwd = f.encrypt(pwd)

#DECRYPT FUNCTION
def decrypt_pwd():
    p = db.session.query(User).filter_by(username="ita_itf").first()
    DESTINATION_PSW = f.decrypt(p.pwd)
    return DESTINATION_PSW

Here I store the pwd in the db, this is all good

#store FTP pwd I ONLY RUN THIS ONES THEN I COMMENT
#DICP_FTP_DESTINATION_PSW = self.submit_pwd()
#db.drop_all()  # destroy all the tables.
#db.create_all()  # create all fresh new tables.
#ftp = User(id = 1, username ="ita_itf", pwd = DICP_FTP_DESTINATION_PSW)
#db.session.add(ftp)
#db.session.commit()

Here's the problem, I call the decrypt_pwd function in my other .py file

from store_user_db import decrypt_pwd
DICP_FTP_DESTINATION_PSW = decrypt_pwd()
0

There are 0 best solutions below