Does not print the error on a wrong key

I somehow set a wrong key for a database, the database cannot be opened but console did not print out the error like below. I remember it did in previous versions.

  • Swift 5
  • pod ‘SQLCipher’, ‘~>4.0’

Thanks.

rc = sqlite3_key(db, password, Int32(password.utf8CString.count))
    if (rc != SQLITE_OK) {
        let errmsg = String(cString: sqlite3_errmsg(db))
        NSLog("Error setting key: \(errmsg)")
    }

@jdleung

Thanks for your interest in SQLCipher and for posting to the discussion forum.

The code you posted won’t generate an error message when provided the incorrect key, an error message will be generated after you attempt to access/operate on the database after providing the incorrect key material.

One way you can handle this is attempting to SELECT FROM sqlite_master table right after keying it to determine if the database is unlocked:

Here’s a brief example:

    func unlockDatabaseTest() {
        openDatabaseWithPassword("correct horse battery staple")
        openDatabaseWithPassword("incorrect horse battery staple")
    }
    
    func openDatabaseWithPassword(_ password : String) {
        var rc: Int32
        var db: OpaquePointer? = nil
        let fileManager = FileManager.default
        var filePath: String? = nil;
        do {
            let documentDirectory = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor:nil, create:false)
            filePath = documentDirectory.appendingPathComponent("test.db").path
        } catch {
            print(error)
        }
        rc = sqlite3_open(filePath, &db)
        if (rc != SQLITE_OK) {
            let errmsg = String(cString: sqlite3_errmsg(db))
            NSLog("Error opening database: \(errmsg)")
            return
        }
        rc = sqlite3_key(db, password, Int32(password.utf8CString.count))
        if (rc != SQLITE_OK) {
            let errmsg = String(cString: sqlite3_errmsg(db))
            NSLog("Error setting key: \(errmsg)")
        }
        rc = sqlite3_exec(db, "SELECT COUNT(*) FROM sqlite_master", nil, nil, nil)
        if (rc == SQLITE_OK) {
            NSLog("DATABASE IS UNLOCKED")
        } else {
            // database isn't unlocked
            let errmsg = String(cString: sqlite3_errmsg(db))
            NSLog("DATABASE ISN'T UNLOCKED: \(errmsg)")
        }
        sqlite3_close(db)
    }

Which outputs:

DATABASE IS UNLOCKED
DATABASE ISN'T UNLOCKED: file is not a database

OK, I may have remembered it wrong.

Thank you.

1 Like