'How does a fernet key work and how to store it safely (Python)?

I am experimenting with Fernet from Cryptography module in Python and encountered certain heavy terms I was not able to understand, despite clear and good documentation of the Cryptography library.

My question is: how does a fernet key works exactly, and how do I use my own passwords as key to fernet class? And how do I store this derived key such that if it is compromised to an attacker, it is hard for the attacker to break it into its original pass phrase?

What I have tried so far :

class Main():

    def __init__(self):

        print("Running Sequences")

    def lock_dir(self, dirc, pwd, zip_name, zip_pwd):#taking directory to lock , the password for fernet , the password for zip and name for the zip

        #declaring all arguments in variables
        self.dirc = dirc
        self.pwd = pwd
        self.zip_name = zip_name
        self.zip_pwd = zip_pwd

        #a separate path for key to be written
        self.key_dirc = self.dirc + "\\key.txt"

        # generating a key from the password
        self.pwd_bytes = self.pwd.encode()
        self.salt = os.urandom(16) #generating salt
        self.kdf = Scrypt(salt = self.salt, length = 32, n = 2**20, r = 8, p = 1)
        self.key = base64.urlsafe_b64encode(self.kdf.derive(self.pwd_bytes))

        self.fernet_object = Fernet(self.key)

        #traversing through the directory provided by the user
        for files in os.listdir(self.dirc):
            with open(os.path.join(self.dirc, files), "rb") as file:
                self.file_data = file.read()
                file.close()

            encrypted_data = self.fernet_object.encrypt(self.file_data)

            with open(os.path.join(self.dirc, files), "wb") as file:
                file.write(encrypted_data)
                file.close()

        with open(self.key_dirc, "wb") as hash_file:
            hash_file.write(self.key)
            hash_file.close()

Now , another question is that would the attacker will be able to use this key.txt as a key to directly decrypt the data encrypted through it, compromising all efforts at vain or will this key.txt will be needed to derived again into a key to decrypt the data ?

Thank you



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source