我在创建新的加密数据库时遇到问题。我已经对此进行了研究,这些是我尝试过的一些解决方案。
使用基于http://sqlcipher.net/design/的终端
sqlite3 sqlcipher.db
sqlite> PRAGMA KEY='test123';
sqlite> CREATE TABLE t1(a,b);
sqlite> INSERT INTO t1(a,b) VALUES ('one for the money', 'two for the show');
sqlite> .quit
~ $ hexdump -C sqlcipher.db
运行 hexdump 仍然给我非加密的数据库文本。
在 ios 中对现有 Db 执行附加方式。
- (void)encryptDB
{
sqlite3 *unencrypted_DB;
NSString *path_u = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]
stringByAppendingPathComponent:@"unencrypted.db"];
if (sqlite3_open([path_u UTF8String], &unencrypted_DB) == SQLITE_OK) {
NSLog(@"Database Opened");
// Attach empty encrypted database to unencrypted database
sqlite3_exec(unencrypted_DB, "ATTACH DATABASE 'encrypted.db' AS encrypted KEY '1234';", NULL, NULL, NULL);
// export database
sqlite3_exec(unencrypted_DB, "SELECT sqlcipher_export('encrypted');", NULL, NULL, NULL);
// Detach encrypted database
sqlite3_exec(unencrypted_DB, "DETACH DATABASE encrypted;", NULL, NULL, NULL);
NSLog (@"End database copying");
sqlite3_close(unencrypted_DB);
}
else {
sqlite3_close(unencrypted_DB);
NSAssert1(NO, @"Failed to open database with message '%s'.", sqlite3_errmsg(unencrypted_DB));
}
}
上面运行没有问题,但 encrypted.db 没有出现在我的文档文件夹中。
在我的应用程序中设置 ssl 和 sqlcipher 之后。使用这个
- (void) openCipherDB
{
NSString *databasePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]
stringByAppendingPathComponent: @"unencrypted.db"];
NSLog(@"database path %@", databasePath);
sqlite3 *db;
if (sqlite3_open([databasePath UTF8String], &db) == SQLITE_OK)
{
//sqlite3_exec(_db, "ATTACH DATABASE 'xyz.sqlite' AS encrypted KEY 'test';", NULL, NULL, &t)
const char* key = [@"secret" UTF8String];
int sqlite3_key(sqlite3 *db, const void *pKey, int nKey); //i added this after seeing SO
sqlite3_key(db, key, strlen(key));
if (sqlite3_exec(db, (const char*) "SELECT count(*) FROM sqlite_master;", NULL, NULL, NULL) == SQLITE_OK) {
// password is correct, or, database has been initialized
NSLog(@"database initialize");
}
else
{
NSLog(@"incorrect pass");
// incorrect password!
}
sqlite3_close(db);
}
}
它给了我不正确密码的 NSLog,当然我的数据库也没有加密。
我还能做些什么来加密我的数据库?谢谢。