tags:

views:

80

answers:

1

Hi everyone,

I have been trying to encrypt/ decrypt a sqlite database in my iPhone project. I am able to encrypt the database by using the reKey method. But I am unable to decrypt it. I have kept my sqlite.db file in a folder. Currently trying it on a simulator.

Code snippet:

[[SQLiteDB sharedSQLiteDB] open: withKey:@""];

[[SQLiteDB sharedSQLiteDB] reKey:@"abc"];

[[SQLiteDB sharedSQLiteDB] close];

[[SQLiteDB sharedSQLiteDB] open: withKey:@"abc"];

[[SQLiteDB sharedSQLiteDB] reKey:@""];

.....

  • (BOOL)open:(NSString *)path withKey:(NSString *)masterKey {

    if (sqlite3_open([path fileSystemRepresentation], &_db) != SQLITE_OK) { NSLog(@"SQLite Opening Error: %s", sqlite3_errmsg(_db)); return NO; }

    if(masterKey) sqlite3_exec(_db, [[NSString stringWithFormat:@"PRAGMA key = '%@'", masterKey] UTF8String], NULL, NULL, NULL);

    if (sqlite3_exec(_db, (const char*) "SELECT count(*) FROM sqlite_master", NULL, NULL, NULL) != SQLITE_OK) { [self close]; NSLog(@"SQLite Key Error!"); return NO; }

    filePath = [path retain]; return YES; }

......

  • (void)reKey:(NSString *)masterKey { sqlite3_exec(_db, [[NSString stringWithFormat:@"PRAGMA rekey = '%@'", masterKey] UTF8String], NULL, NULL, NULL);

}

I have read the posts on this topic in sqlcipher google groups, but I am unable to decrypt it. Any help would be highly appreciated.

A: 

Reposing from the mailing list:

If you are trying to take an existing non-encrypted database, encrypt it, and then decrypt it back, our recommended approach is not to use rekey, but instead to use ATTACHed databases to copy data between a standard and an sqlcipher database. There is more information and a concrete example here:

http://www.zetetic.net/blog/2009/12/29/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher/

If instead, you are just trying to use sqlcipher to encrypt data in general (i.e. with no conversion from a pre-existing database), then you just need to use sqlite3_key. You basically just open the database, provide the key and then make sql calls. There are no separate encryption / decryption steps - all of that is handled on the fly by the sqlcipher code. In the code you posted previously, you'd never call rekey at all. Each time you open the database you call PRAGMA key, and then run a quick check to ensure that sqlite_master is readable.

Stephen Lombardo
Thanks, first approach worked in my case.