pythonfernetsqlite3-python

Python, fernet decrypt turn my file read only


I'm with a personal proyect using python and sqlite3, the case is that i use fernet to encrypt the db file, but at decrypt the db it turn in a read only db and give me error at try do an INSERT.

sqlite3.OperationalError: attempt to write a readonly database

I try edit the linux permissions using chmod 664 and 777 but nothing seems work it still as only read db

----- EDIT WITH MORE INFO

I use local file and connect using sqlite3, i create a clase for manage the db

class DataBaseManager(object):
    def __init__(self,db):
        self.con = sqlite3.connect(db)
        self.cur = self.con.cursor()

    def inicializar(self):
        checkTableStore = self.cur.execute(
            """SELECT name FROM sqlite_master WHERE type='table' AND name='store'; """
        ).fetchall()
        if checkTableStore == []:
            self.cur.execute(
                """create table store(
                    ........
                )"""
            )

    def __del__(self):
        self.con.close

if in the first execution and the db file doesn't exist create it with the DataBaseManager(dbfile) and after check if the table that i need is created or not and create if not exist with DataBaseManager.inicializar()

keyfile = input("keyfile: ")
dbfile = "pstore.db"
dbencrypt = "pstore.enc"
dbm = DataBaseManager(dbfile)
DataBaseManager.inicializar()

For encrypt and decrypt i use a key generated with fernet

def encryptdb(keyfile, dbfile, dbencrypt):
    with open(keyfile, "rb") as openkeyfile:
        key = openkeyfile.read()

    fernet = Fernet(key)

    with open (dbfile, "rb") as opendbfile:
        decrypteddb = opendbfile.read()

    encrypted = fernet.encrypt(decrypteddb)

    with open (dbencrypt, "wb") as encrypteddb:
        encrypteddb.write(encrypted)


def decryptdb(keyfile, dbfile, dbencrypt):
    with open(keyfile, "rb") as openkeyfile:
        key = openkeyfile.read()

    fernet = Fernet(key)

    with open (dbencrypt, "rb") as openenc:
        encrypteddb = openenc.read()

    decrypted = fernet.decrypt(encrypteddb)

    with open (dbfile, "wb") as decrypteddb:
        decrypteddb.write(decrypted)

Before than made the encrypt i can do inserts without problem, but after encrypt and decrypt i got the problem that the database is only read


Solution

  • Ok, solved.

    I tryed use a second file to save the db encrypted. But i proved save the encrypted output of fernet in the sabe db file that existed, it don't give to me the ro error after decrypt.