Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlite random file is encrypted or is not a database

Tags:

sqlite

ios

iphone

I have an application that frequently accesses a sqlite database. It works great most of the time but occasionally in one of my database functions fails and returns:

file is encrypted or is not a database

I don't have any encryption enabled but I can't pinpoint how this is happening. It's not consistently reproducible and from the crash logs, it happens on the main thread.

Thanks in advance.

@synchronized(self) {
    sqlite3 *database = mydb;
    int result = 0;

    static sqlite3_stmt *stmt = nil;
    if (stmt == nil) {
        const char *sql = "select sum(not isAvailable) from table1 e inner join table2 f on e.key=f.pk where f.pk=? AND e.isDeleting=0;";
        if (sqlite3_prepare_v2(database, sql, -1, &stmt, NULL) != SQLITE_OK) {
            NSAssert1(0, @"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
        }
    }

    sqlite3_bind_int(stmt, 1, obj.primaryKey);

    if (sqlite3_step(stmt) == SQLITE_ROW) {
        int val = sqlite3_column_int(stmt, 0);
        result = val;
    } else {
        [NSException raise:@"SQL Fail" format:@"SQL Failed: %s", sqlite3_errmsg(database)];
    }
    // Reset the statement for future reuse.
    sqlite3_reset(stmt);

    return result;
}
like image 225
VTS12 Avatar asked Nov 12 '22 11:11

VTS12


1 Answers

To create a new encrypted SQLite database or to open an existing encrypted SQLite database you have to call the function sqlite3_key or to execute a "pragma key=" command immediately after opening the database before performing any other database operation. I suspect that you tried to open an existing database, but not encrypted SQLite database and expected to encrypt it by using one of the above methods. This doesn't work but results in the error message you experienced. To encrypt an existing not encrypted SQLite database you have to use function sqlite3_rekey or "pragma rekey=" command. To change the encryption key of an existing encrypted SQLite database you have to open the database, then to use sqlite3_key (or "pragma key=") and then to apply sqlite3_rekey (or "pragma rekey=").

like image 71
iVenky Avatar answered Nov 15 '22 05:11

iVenky