I'm trying to add the contents of an unencrypted sqlite3 database to an encrypted one using SQLCipher. I've based what I am trying to do off of this and this. A few things however remain unclear to me.
In line
ATTACH DATABASE
, does the encrypted database have to be of type.db
? Can it be.sqlite
to match my original database?Does said encrypted database have to already exist? If so, where should it be in the app? Do I have to provide a path to the file (documents directory, etc)?
Where can I find the successfully encrypted database? Where will it be saved?
Here is my code:
+ (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));
}
}
REKEY
to encrypt an existing DB. Our SQLCipher implementations handleREKEY
of an existing DB just fine. – Hefner