我正在使用 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(数据库已加密或不是数据库文件)。