· 7 years ago · Sep 03, 2018, 04:58 AM
1NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
2NSString *documentDir = [documentPaths objectAtIndex:0];
3NSString *ecDB = [documentDir stringByAppendingPathComponent:@"encrypted.sqlite"];
4
5// SQL Query. NOTE THAT DATABASE IS THE FULL PATH NOT ONLY THE NAME
6const char* sqlQ = [[NSString stringWithFormat:@"ATTACH DATABASE '%@' AS encrypted KEY 'Pank123';",ecDB] UTF8String];
7
8sqlite3 *unencrypted_DB;
9if (sqlite3_open([databasePath UTF8String], &unencrypted_DB) == SQLITE_OK) {
10
11 // Attach empty encrypted database to unencrypted database
12 sqlite3_exec(unencrypted_DB, sqlQ, NULL, NULL, NULL);
13
14 // export database
15 sqlite3_exec(unencrypted_DB, "SELECT sqlcipher_export('encrypted');", NULL, NULL, NULL);
16
17 // Detach encrypted database
18 sqlite3_exec(unencrypted_DB, "DETACH DATABASE encrypted;", NULL, NULL, NULL);
19
20 sqlite3_close(unencrypted_DB);
21}
22else {
23 sqlite3_close(unencrypted_DB);
24 NSAssert1(NO, @"Failed to open database with message '%s'.", sqlite3_errmsg(unencrypted_DB));
25}
26
27databasePath = [documentDir stringByAppendingPathComponent:@"encrypted.sqlite"];
28
29
30
31
32
33sqlite3 *db;
34sqlite3_stmt *stmt;
35bool sqlcipher_valid = NO;
36
37if (sqlite3_open([databasePath UTF8String], &db) == SQLITE_OK)
38{
39 const char* key = [@"Pank123" UTF8String];
40 sqlite3_key(db, key, (int)strlen(key));
41
42 NSLog(@"%d", sqlite3_exec(db, (const char*) "SELECT count(*) FROM sqlite_master;", NULL, NULL, NULL));
43
44 if (sqlite3_exec(db, (const char*) "SELECT count(*) FROM sqlite_master;", NULL, NULL, NULL) == SQLITE_OK)
45 {
46 if(sqlite3_prepare_v2(db, "PRAGMA cipher_version;", -1, &stmt, NULL) == SQLITE_OK)
47 {
48 if(sqlite3_step(stmt)== SQLITE_ROW)
49 {
50 const unsigned char *ver = sqlite3_column_text(stmt, 0);
51 if(ver != NULL)
52 {
53 sqlcipher_valid = YES;
54
55 // password is correct (or database initialize), and verified to be using sqlcipher
56
57 }
58 }
59 sqlite3_finalize(stmt);
60 }
61 }
62 sqlite3_close(db);
63}
64
65
66
67 const char *dbpath=[databasePath UTF8String];
68 if(sqlite3_open(dbpath, &db)==SQLITE_OK)
69 {
70 char *errmsg;
71 const char* key = [@"Pank123" UTF8String];
72 sqlite3_key(db, key, (int)strlen(key));
73
74 const char *sql_stmt = "CREATE TABLE IF NOT EXISTS EVENT(EVENTID INTEGER PRIMARY KEY AUTOINCREMENT,ENAME TEXT,ETIME TEXT,TIMAGE TEXT)";
75 NSLog(@"%d", sqlite3_exec(db,sql_stmt,NULL,NULL,&errmsg));
76 if(sqlite3_exec(db,sql_stmt,NULL,NULL,&errmsg)!=SQLITE_OK)
77 {
78 NSLog(@"yes");
79 }
80 sqlite3_close(db);
81 }
82 else
83 {
84 NSLog(@"failed to open/create database");
85 }