gpt4 book ai didi

iphone - 使用 SQLCipher 将加密数据库附加到未加密数据库

转载 作者:IT王子 更新时间:2023-10-29 06:27:39 26 4
gpt4 key购买 nike

我正在尝试使用 SQLCipher 将未加密的 sqlite3 数据库的内容添加到加密的数据库中。我基于我想做的事情 thisthis .然而,我仍然不清楚一些事情。

  1. ATTACH DATABASE 行中,加密的数据库是否必须是 .db 类型?可以是.sqlite来匹配我原来的数据库吗?

  2. 上述加密数据库必须已经存在吗?如果是这样,它应该在应用程序中的什么位置?我是否必须提供文件路径(文档目录等)?

  3. 在哪里可以找到成功加密的数据库?保存在哪里?

这是我的代码:

+ (void)encryptDB
{
sqlite3 *unencrypted_DB;
NSString *path_u = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]
stringByAppendingPathComponent:@"dict.sqlite"];

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 'dict_encrypted.sqlite' AS encrypted KEY '1234';", NULL, NULL, NULL);

// Create new tables within encrypted database to match those in unencrypted database
sqlite3_exec(unencrypted_DB, "CREATE TABLE encrypted.t1(A,B,C);", NULL, NULL, NULL);

// Copy items from unencrypted database into encrypted database
sqlite3_exec(unencrypted_DB, "INSERT INTO encrypted.t1 SELECT * FROM t1;", 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));
}
}

最佳答案

使用最新版本的 SQLCipher,我们有 sqlcipher_export() 函数,它可以使我们的代码更短并且不连接到现有的数据库结构:

+ (void)encryptDB
{
sqlite3 *unencrypted_DB;
NSString *path_u = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]
stringByAppendingPathComponent:@"dict.sqlite"];

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 'dict_encrypted.sqlite' 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));
}
}

关于iphone - 使用 SQLCipher 将加密数据库附加到未加密数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8931555/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com