SQLCipher ATTACH使用自定义cipher_page_size加密数据库

时间:2013-01-19 19:16:34

标签: sql sqlite sqlcipher

我正在使用SQLCipher加密SQLite数据库。我似乎遇到了使用自定义cipher_page_size(不同于默认值1024)来加密数据库的麻烦。

这是我的代码

- (void) database:(sqlite3*) database execute:(NSString*) sql {
    if (sqlite3_exec(database, [sql UTF8String], NULL, NULL, NULL) == SQLITE_OK) {
        NSLog(@"\"%@\" successfully executed", sql);
    } else {
        NSLog(@"Could not execute \"%@\" (%s)", sql, sqlite3_errmsg(database));
    }
}

- (void)test {

    sqlite3 *database1;
    sqlite3 *database2;

    NSString *path1 = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]
                        stringByAppendingPathComponent:@"database1.sqlite"];
    NSString *path2 = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]
                        stringByAppendingPathComponent:@"database2.sqlite"];

    if (sqlite3_open([path1 UTF8String], &database1) == SQLITE_OK) {
        NSLog(@"database1 opened successfully");
        [self database:database1 execute:@"PRAGMA key = 'password1';"];
        //[self database:database1 execute:@"PRAGMA cipher_page_size = 2048;"];
        [self database:database1 execute:@"CREATE TABLE IF NOT EXISTS table1 (id INTEGER PRIMARY KEY, name TEXT);"];
        [self database:database1 execute:@"INSERT INTO table1 (name) VALUES ('bob');"];
        sqlite3_close(database1);
    } else {
        sqlite3_close(database1);
        NSLog(@"Failed to open database1 with message '%s'.", sqlite3_errmsg(database1));
    }

    if (sqlite3_open([path2 UTF8String], &database2) == SQLITE_OK) {
        NSLog(@"database2 opened successfully");
        [self database:database2 execute:@"PRAGMA key = 'password2';"];
        //[self database:database2 execute:@"PRAGMA cipher_page_size = 2048;"];
        [self database:database2 execute:@"CREATE TABLE IF NOT EXISTS table2 (id INTEGER PRIMARY KEY, name TEXT);"];
        [self database:database2 execute:@"INSERT INTO table2 (name) VALUES ('john');"];

        [self database:database2 execute:[NSString stringWithFormat:@"ATTACH DATABASE '%@' AS database1 KEY 'password1';", path1]];
        [self database:database2 execute:@"DETACH DATABASE database1;"];

        sqlite3_close(database2);
    } else {
        sqlite3_close(database2);
        NSLog(@"Failed to open database2 with message '%s'.", sqlite3_errmsg(database2));
    }
}

当注释有关更改cipher_page_size的行时,代码按预期工作。当它们被注释掉时,我得到错误SQLITE_NOTADB(数据库已加密或不是数据库文件)。

1 个答案:

答案 0 :(得分:1)

您应该在附加数据库后立即明确设置附加数据库的页面大小,即:

ATTACH DATABASE 'db1.db' AS database1 KEY 'password1';
PRAGMA database1.cipher_page_size = 2048;
相关问题