1

我刚刚在我的应用程序中实现了 SQLCipher 来加密一个相当简单的数据库。我仔细按照教程中的所有设置说明进行操作,项目正在构建并且应用程序正在成功运行。但是,当我使用他们的示例代码加密我的数据库时,我的密码不正确,我现在无法打开我的数据库。这是代码:

NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] 
                      stringByAppendingPathComponent: @"dict.sqlite"];
if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
        const char* key = [@"BIGSecret" UTF8String];
        sqlite3_key(database, key, strlen(key));
        if (sqlite3_exec(database, (const char*) "SELECT count(*) FROM sqlite_master;", NULL, NULL, NULL) == SQLITE_OK) {
            // password is correct, or, database has been initialized
            NSLog(@"Correct Password :)");
        } 
        else {
            // incorrect password!
            NSLog(@"Incorrect Password :(");
        }
    }
    else {
        sqlite3_close(database);
        NSAssert1(NO, @"Failed to open database with message '%s'.", sqlite3_errmsg(database));
    }
}

sqlite3 *database;在我的界面中声明。我的应用程序在这条线上崩溃:

if (sqlite3_prepare_v2(database, sql, -1, &init_statement, NULL) != SQLITE_OK) {
    NSAssert1(NO, @"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
}

在没有加密的情况下一切正常,所以我的其余代码没有问题。控制台在崩溃前打印“Incorrect Password :(”。崩溃日志是:Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Error: failed to prepare statement with message 'file is encrypted or is not a database'.'密码明显存在问题。有帮助吗?

谢谢。

4

1 回答 1

1

最可能的问题是您试图在尚未加密的现有数据库 dict.sqlite 上设置密钥。sqlite3_key 函数不加密现有数据库。如果要加密现有数据库,则需要附加一个新的加密数据库并在两者之间移动数据,如下所述:

http://zetetic.net/blog/2009/12/29/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher/

或者,使用 SQLCipher 2,您可以使用 sqlcipher_export,它提供了一种在数据库之间移动数据的简单方法。:

http://groups.google.com/group/sqlcipher/msg/76d5b03426419761

于 2012-01-18T22:26:40.387 回答