Encrypting a database with Sqlcipher

Source: Internet
Author: User

Xcode integrates a free sqlite, but does not provide an encrypted module, and suddenly one day, the egg-hurting customer asks to encrypt the data, looking for a framework that is simple to use and can migrate data over to an encrypted database. Sqlcipher is a third-party open source framework, to achieve the encryption of SQLite, website link: http://sqlcipher.net. Download and import the framework below. (download using the command line) one, use Sqlcipher need 3 files: sqlcipher,openssl-xcode,openssl-1.0.0e download Openssl-xcode
CD ~/documents/code/sqlcipherappgit clone Https://github.com/sqlcipher/openssl-xcode.git

Download Sqlcipher

CD ~/documents/code/sqlcipherappgit clone Https://github.com/sqlcipher/sqlcipher.git

Download openssl-1.0.0e

Curl-o openssl-1.0.0e.tar.gz http://www.openssl.org/source/openssl-1.0.0e.tar.gz//Unzip tar xzf openssl-1.0.0e.tar.gz

Copy these three directories into the project catalog

Two. Configure Xcode

1, open the Xcode settings page, enter locations->source trees, click the + sign to add items, Settingname and display name are set to "OPENSSL_SRC" Path settings for your project directory opens The path where the sl-1.0.0e is located. For example, my path is:/users/henry/documents/Project public/sqlcipherapp/openssl-1.0.0e

  

2, add a reference to the project, the files in the Openssl.xcodeproj and Sqlcipher.xcodeproj (respectively, openssl-xcode files and sqlcipher files) added to your main project, set up a reference 3, the configuration of the compilation library, Enter project targets, enter build phases->target dependencies, add two items in the diagramlink binary with libraries add these two librariesThird, the following example to use the first need to introduce a header file import<sqlite3.h>
//functions to open a database+(BOOL) opendb {Nsarray*patharr =nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES); NSString*docpaths = [Patharr objectatindex:0]; NSString*dbpath = [Docpaths stringbyappendingformat:@"/mydb.db"]; intStatus = Sqlite3_open ([DbPath utf8string], &gb_db); if(Status! =SQLITE_OK) {Log_cinfo (@"Error opening Database! "); db_opened=NO; returndb_opened; } db_opened=yes;sqlite3_stmt*statement;#ifUsease//To verify that the SQL statement is successful    Const Char*key =[[GlobalData getinstance].    Gb_dbkey utf8string]; Sqlite3_key (gb_db, Key, strlen (key));#endif    if(Sqlite3_prepare_v2 (gb_db, [SQL Utf8string],-1, &statement, nil)! =SQLITE_OK) {Log_cinfo (@"failed to create TABLE! "); returnNO; }    intSuccess =sqlite3_step (statement);    Sqlite3_finalize (statement); //[MyDataBase closedb];    if(Success! =Sqlite_done) {Log_cinfo (@"An error occurred during the creation of the table, the creation was not finished! "); returnNO; }        returnYES;}
Create Required data table + (void) createneedtable {    @autoreleasepool {        //Insert User Information table        localdatabase *USERTB = [localdatabase gettablewithtype:@ "user" hasuser:no];            First create               [USERTB createtablewithkeys:[nsarray arraywithobjects:@ "userid", Nil] Otherneeds:[nsarray arraywithobjects:@ "SiteID", @ "username", @ "password", @ "Mobilephone", @ "name", Nil] data:nil];}

Create a table from the parameters, keys is the primary key, needs are those non-primary keys, but must be required, such as the need to sort, search for the field, data is the whole form of information items, using data is to reduce the number of fields-(BOOL) Createtablewithkeys        :(Nsarray *) keys otherneeds: (Nsarray *) needs data: (NSString *) data {//If there is a message stating that the registration was successful already if (Self.mytableinfo) {    return YES; }//First make sure that the database is open if (![    LocalDatabase Opendb]) {return NO;    }//write all non-data fields into an array nsmutablearray *allarr = [Nsmutablearray arraywithcapacity:10];    if ([keys Count] > 0) {[Allarr Addobjectsfromarray:keys];    } if ([needs count] > 0) {[Allarr addobjectsfromarray:needs];    } if (Self.hasuser) {[Allarr insertobject:@ "UserName" atindex:0];    } int keyscount = [Allarr count];    if (Self.mytableinfo = = nil) {self.mytableinfo = [Nsmutablearray arraywithcapacity:keyscount+1];        }//Insert data for (int i = 0; i < keyscount;++i) {nsstring *key = [Allarr objectatindex:i]; [Self.mytableinfo addobject:[nsdictionary dictionarywithobjectsandkeys:@]Text ", @" type ", key,@" key ", Nil]]; }//Create SQL statement nsmutablestring *csql = [nsmutablestring stringwithformat:@ "CREATE table if not exists%@ (", self.mytabl    ENAME];    Add a non-data type field to the SQL statement for (NSString *key in Allarr) {[Csql appendformat:@ "%@ text,", Key];        }//Add the field of the data type to the SQL statement if (data = nil) {[Csql appendformat:@ "%@ blob,", data];    [Self.mytableinfo addobject:[nsdictionary dictionarywithobjectsandkeys:@ "blob", @ "type", data,@ "key", Nil]];    }//Add primary key [Csql appendstring:@ "PRIMARY key ("];    int keycount = [keys count]; if (Keycount > 0)//case with multiple primary keys {for (int i = 0; i < keyCount-1; ++i) {NSString *key = [k             Eys OBJECTATINDEX:I];        [Csql appendformat:@ "%@,", Key];        } if (Self.hasuser) {[Csql appendstring:@ "userName,"];    } [Csql appendformat:@ "%@)", [Keys objectatindex:keycount-1];       } else {//if (Keycount = = 1)//Only one primary key case//{//     [Csql appendformat:@ "%@)", [keys objectatindex:0]];//}//else {if (self.hasuser)            {[Csql appendstring:@ "UserName)"];    }}} [Csql appendstring:@ "];    Log_cinfo (@ "========sql Statement creation Table =========");    Log_cinfo (CSQL);        {Nsmutabledictionary *dic = (nsmutabledictionary *) [Globalfunc parsedicfromfile:@ "Dbinfo.plist"];        if (dic = = nil) {dic = [nsmutabledictionary dictionarywithcapacity:1];        } [dic SetObject:self.myTableInfo forKey:self.myTableName];    [Globalfunc writedictofile:dic filename:@ "Dbinfo.plist"]; } return [LocalDatabase createtablewithsql:csql];}

 

Insert data into table-(bool) Insertdatawithdic: (nsdictionary *) dic Replace: (BOOL) Replace {//Open database if (! db_opened) {if (![ LocalDatabase Opendb]) {Log_cinfo (@) failed to insert data, error opening database!            ");        return NO;    }} nsmutabledictionary *tmpdic = [Nsmutabledictionary dictionarywithdictionary:dic]; if (self.hasuser) {[Tmpdic setobject:[globaldata getinstance].    Gb_username forkey:@ "UserName"];    } nsmutablearray *allkeys = [Nsmutablearray arraywitharray:[tmpdic AllKeys];    Nsmutablestring *csql = nil; Generate INSERT statement if (replace) {csql = [nsmutablestring stringwithformat:@ "insert or replace into%@ (", Self.mytablena    Me];    } else {csql = [nsmutablestring stringwithformat:@ "INSERT INTO%@ (", self.mytablename];    } int keyscount = [AllKeys count]; if (Keyscount > 0) {for (int i = 0; i < keyscount-1;++i) {[Csql appendformat:@ "%@,", [Al        Lkeys Objectatindex:i]]; } [Csql Appendformat:@ "%@)", [AllKeys objectatindex:keyscount-1]];    } else {return NO;    } [Csql appendstring:@ "values ("];    for (int i = 0; i<keyscount-1; ++i) {[Csql appendstring:@ "?,"];    } [Csql appendstring:@ "?)"];    Log_cinfo (@ "========sql statement Insert Table =========");    Log_cinfo (CSQL);    Test whether the SQL statement is correct sqlite3_stmt *statement; const char *insertstatement = [Csql utf8string]; #if usease//Verify that the SQL statement succeeds const char *key = [[GlobalData getinstance] .    Gb_dbkey utf8string];  Sqlite3_key (gb_db, Key, strlen (key)), #endif if (Sqlite3_prepare_v2 (gb_db, Insertstatement,-1, &statement, NULL)! = SQLITE_OK) {Log_cinfo (@) failed to insert data into the table, possibly the SQL statement is incorrect!        ");        [Globalfunc shownormalalert:[nsstring stringwithformat:@] failed to insert data into table, possibly SQL statement is incorrect, table name is%@ ", Self.mytablename]];    return NO;        } for (int i = 0; i < keyscount;++i) {nsstring *key = [AllKeys objectatindex:i];        ID value = [tmpdic Objectforkey:key]; If the data type if ([Value Iskindofclass:[nsdata class]])        {Sqlite3_bind_blob (statement, i+1, [value bytes], [value length], NULL);        } else//is a string type {Sqlite3_bind_text (statement, i+1, [value utf8string],-1, NULL);    }} int success = SQLITE3_STEP (statement);    Release Resources sqlite3_finalize (statement); if (success = = Sqlite_error) {log_cinfo (@) failed to insert data into table, unknown reason ended prematurely!        ");        [Globalfunc shownormalalert:[nsstring stringwithformat:@] inserted data into the table failed, unknown cause early end, table named%@ ", Self.mytablename]];    return NO; } log_cinfo (@) inserted data into the table successfully!    "); return YES;}

 

Update table fields, key is the name of the field to update, NewValue is the value to be designed after the update, where is the condition (in the SQL statement), condition is the condition that satisfies the update, if use uses the user name condition-(BOOL) Updaterecordwithkey: (NSString *) key Value: (NSString *) newvalue Where: (NSString *) where Condition: (NSString *) Condition Useuser: (BOOL) use {if (![    LocalDatabase Opendb]) {return NO;        } @try {NSString *tmpupdatesql = nil; if (use && self.hasuser) {tmpupdatesql = [nsstring stringwithformat:@ "UPDATE%@ SET%@ =? whe Re%@ =?        and UserName =? ", Self.mytablename,key,where]; } else {tmpupdatesql = [nsstring stringwithformat:@ "UPDATE%@ SET%@ =? where%@ =?", Self.myta blename,key,where];//@ "UPDATE tb_bulletlist SET has_read =? where Bulletin_code =?        and user_name=? ";}        Sqlite3_stmt *statement;        Log_cinfo (@ "========sql Statement Update table ========="); Log_cinfo (tmpupdatesql); #if usease//Verify that the SQL statement succeeds const char *key = [[GlobalData getinstance].        Gb_dbkey utf8string]; SqliTe3_key (gb_db, Key, strlen (key)), #endif if (SQLITE3_PREPARE_V2 (gb_db, [Tmpupdatesql utf8string], 1, &statement, NIL)! = SQLITE_OK) {log_cinfo (@) failed to update the data!             ");            [Globalfunc shownormalalert:[nsstring stringwithformat:@ "Update data failed with table named%@", Self.mytablename]];        return NO;        } sqlite3_bind_text (statement, 1, [NewValue utf8string],-1, NULL);        Sqlite3_bind_text (statement, 2, [condition utf8string],-1, NULL); if (use && self.hasuser) {sqlite3_bind_text (statement, 3, [[GlobalData getinstance].        Gb_username utf8string],-1, NULL);        } int success = SQLITE3_STEP (statement);        Sqlite3_finalize (statement);        [MyDataBase Closedb]; if (Success! = Sqlite_done) {log_cinfo (@) failed to update data, unknown reason ended prematurely!             ");            [Globalfunc shownormalalert:[nsstring stringwithformat:@ "Update data failed, unknown cause early end, table named%@", Self.mytablename]];        return NO; }} @catch (NSException *e) {//Log_cerr (e); } return YES;

 

Based on the values of the keywords and keywords passed in, a record is obtained, and if there is no record, return to nil, the estimate can also be used to determine if there is a record, using the user name condition-(Nsmutabledictionary *)    Getonerecordwithkeys: (Nsarray *) keys values: (Nsarray *) values Useuser: (BOOL) use {if ([keys count]! = [Values count]) {//[Globalfunc shownormalalert:[nsstring stringwithformat:@ "getonerecordwithkeys data query parameters keys are inconsistent with values, table name is%@", s        Elf.mytablename]];    return nil; }//Open database if (! db_opened) {if (![ LocalDatabase Opendb] {log_cinfo (@) failed to query data, open database error!            ");        return nil;    }} nsmutablestring *csql = [nsmutablestring stringwithformat:@ "select * from%@ where", Self.mytablename]; if (use && self.hasuser) {[Csql appendformat:@ ' userName = '%@ ' and ', [GlobalData getinstance].    Gb_username];    } int keycount = [keys count]; for (int i = 0; i < Keycount; ++i) {if (i = = 0) {[Csql appendformat:@ "%@ = '%@ '", [Keys OB        Jectatindex:i],[values Objectatindex:i]]; } Else {[Csql appendformat:@ "and%@ = '%@ '", [Keys Objectatindex:i],[values objectatindex:i]];    }} Nsarray *tmparr = [self getdataarrwithsql:csql];    if ([tmparr count] = = 0) {return nil;    } else {return [Tmparr objectatindex:0]; }}

If prompted at compile time: No architectures to compile for (ARCHS=ARMV6,ARMV7, Valid_archs=armv7 armv7s will be in Bulid The settings option below the architectures and valid architectures inside are changed to the same (for example: all fill armv6 armv7), problem solving. For warning: warning:implicit declaration of function ' Sqlite3_key ' is invalid in C99 only need to be bulid settings option under C Language diale CT: c89[-std-c89] can be used, that is, the use of c89 standard

Or remove the arm64 from the project.

The above is just a part of the code, may seem a little hard, and later will be a complete use of the database of the class to sort out.

This article references: http://blog.csdn.net/kuai0705/article/details/8931996

Encrypting a database with Sqlcipher

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.