How to use Python to connect to SQLCipher 4

I’m trying to use Python’s pysqlcipher3.dbapi2 to connect to an SQLCipher 4 encrypted database. I can use the DB Browser for SQLCipher to decrypt and browse it, but I can’t use Python to connect to it.

Below is my Python code:

def connect_db(db_path, db_passwd):
    conn = sqlite.connect(db_path)
    cursor = conn.cursor()
    cursor.execute(f"PRAGMA key = '{db_passwd}';")
    cursor.execute("PRAGMA cipher_page_size = 4096;")
    cursor.execute("PRAGMA kdf_iter = 256000;")
    cursor.execute("PRAGMA cipher_hmac_algorithm = HMAC_SHA512;")
    cursor.execute("PRAGMA cipher_kdf_algorithm = PBKDF2_HMAC_SHA512;")
    return conn


def parser_msg(msg_db, msg_db_passwd):
    print(msg_db, msg_db_passwd)
    cursor = connect_db(msg_db, msg_db_passwd).cursor()
    cursor.execute("SELECT count(*) FROM sqlite_master;")
    print("Database opened successfully.")
    rows = cursor.fetchall()
    print(rows)

The error is as follows

    cursor.execute("SELECT count(*) FROM sqlite_master;")
pysqlcipher3.dbapi2.DatabaseError: file is encrypted or is not a database  

I have also tried the following code, but get the same error

conn = sqlite.connect(encrypted_db_path)
conn.execute(f"PRAGMA key = '{key}'")
conn.execute("PRAGMA cipher_migrate;")
try:
    conn.execute("SELECT count(*) FROM sqlite_master;")
    print("Database decrypted successfully!")
except sqlite.DatabaseError as e:
    print(f"Failed to decrypt database: {e}")
    conn.close()
    exit()

wrong

Failed to decrypt database: file is encrypted or is not a database

@In17 I would suggest executing the statement PRAGMA cipher_version; from your python program. First, check that you get a version number back. If you don’t then an incorrect, non-SQLCipher library has been loaded. If you do get a version back, make sure it is greater than version 4, as that will be required for HMAC_SHA512 support.