Detailed SQL database file encryption (using Sqlcipher) in IOS _ios

Source: Internet
Author: User
Tags openssl openssl library rowcount sql error sqlite strlen goagent

I was going to write a gae+goagent+switchysharp guide today! But then suddenly out of the previous period of time to write about the SQL database files in iOS encryption code, so decided to talk about this today! ~ So Goagent will be on weekends, in addition to file encryption in subsequent articles, as well as the transmission of data encryption, interested in children's shoes please note.

To start with, SQL file encryption, we first need to use a library, it is the famous sqlcipher, attached: Http://sqlcipher.NET, in iOS we need to see the document is this one http://sqlcipher.Net/ ios-tutorial/, the document is all in English, this, does not elaborate, only steps to teach everyone how to do, as to why do the problem, you need to find the answer!
1. Download required libraries Here we need a total of 3 directory files, respectively, is sqlcipher,openssl-xcode,openssl-1.0.0e.
First Download First

% CD ~/documents/code//command line CD to the directory you want to download 
% Curl-o openssl-1.0.0e.tar.gz http://www.openssl.org/source/ openssl-1.0.0e.tar.gz//Download 

Report:

Sqlcipher uses the widely trusted and peer-reviewed OpenSSL library for all cryptographic functions including the AES-256 Algorithm, pseudo random number generation, and PBKDF2 key derivation. OpenSSL isn ' t framework that's usable directly on the IPhone so we'll setup our project to build and link against it as A static library.

Download the 1.0.x stable version from Http://www.openssl.org/source/and extract it to a folder on your system. Since the same OpenSSL source tree May is shared across multiple sqlcipher projects, it's a good idea to place this in SOM E shared location outside of your project folder. Justs make a note to the source directory path for later.

(Do not understand English children's shoes do not worry, and then continue to do good, but also very good understanding)

OpenSSL is a set of open source SSL kits, which are written in C language to achieve basic transport data encryption capabilities.

A second

% CD ~/documents/code/sqlcipherapp 

Clone it from a remote server, it is recommended to put it in the same directory as the previous file for easy management

This is Sqlcipher's project code.

A third

% CD ~/documents/code/sqlcipherapp 

This is the file we need to dynamically compile into the project

So we're ready for the paperwork we need.

Next, open your project for configuration,

(Here I wrote a single tool for encrypting and generating it myself!) The following will be attached to my source code)

1. Copy the 3 directories you downloaded into your engineering directory

2. Click on your Xcode settings page to select locations->source trees

Click the + number Settingname and display name to "OPENSSL_SRC" path set to the location of the openssl-1.0.0e in your engineering directory

3. Add a reference to a child item

Add the Openssl.xcodeproj and sqlcipher.xcodeproj in the file that you just downloaded (under Openssl-xcode files and sqlcipher files) to your main project, build the reference, and look directly at the picture!

4, next configure the build dependent library, which is required! ~

Click on your project targets into build phases->target dependencies, add two items in the diagram

Next click link Binary with libraries under the same page to add both libraries

The final step is to set the compilation settings

Click on your project project->build settings-> search architectures to set

I'm here because it's a Mac program that looks like this.

That's what iOS would be like.

(For the settings here, if you do not understand the place please google)

Next, search for "Other C flags" on the same page.

Configure the following

So far, the whole process has been working.

Next, let's talk about using

First import<sqlite3.h> in the desired file

The following example shows a function that creates or opens a database

-(BOOL) OpenDatabase {if (Sqlite3_open ([self datafilepath:db_name] utf8string], &_database) = = SQLITE_OK) {  Const char* KEY = [@ ", 66c9a^n" utf8string];   Database file encryption Sqlite3_key (_database, key, (int) strlen (key)); 
    Database file encryption NSLog (@ "\n=== database open or create successful ===\n"); 
  return YES; 
  }else{NSLog (@ "\n=== database open failed ===\n"); 
} return NO; Db_name is the macro that defines the database filename ", 66c9a^n" is the database key you want to set Sqlite3_key (_database, key, (int) strlen (key); This method contains the process of adding and decrypting! ~ is not very simple, hey! Next to attach their own project source code has the need for children's shoes, just look at it! There are detailed comments, but also simple to implement a number of functions to facilitate database operations//////////////////////////////////////////////////////////#import <foundation/ foundation.h> #import <sqlite3.h> #define DB_NAME @ "xxxxxxx.db"//Database file name @interface sqlitehelp:n            Sobject @propertysqlite3 *database;         Database handle @propertysqlite3_stmt *statement; 
SQL statement @property char *errmsg;               -(BOOL) OpenDatabase;               Open the database This function is not called directly, but directly calls the function of the database operation-(void) closeDataBase; Close Database ThisFunctions are generally not called directly, but directly invoke functions that operate on the database-(NSString *) DataFilePath: (NSString *) fileName; Returns the database store path This function is not called directly, but rather calls directly on the function of the database operation/** * Description: For a given SQL statement insert or edit a data * statement format: * insert: [insert (filename) VALUES (data1, DAT A2, data3, ...); 
      
] * EDIT: [Update (filename) Set (field name) = (modified data) where (field name) = (data before modification);] */-(BOOL) Insertorupdatedata: (NSString *) SQL;           -(Nsmutablearray *) getusers;             Take an array of the situation, get all users-(int) getcountofdatabase; Gets the number of current databases @end////////////////////////////////////////////////////#import "SqliteHelp.h" @implementation 
Sqlitehelp @synthesize database =_database; 
@synthesize statement =_statement; 
@synthesize errmsg =_errmsg; -(BOOL) OpenDatabase {if (Sqlite3_open ([[selfdatafilepath:db_name]utf8string], &_database) ==SQLITE_OK) {Co  nstchar* key = [@ ", 66c9a^n" utf8string];   Database file encryption Sqlite3_key (_database, key, (int) strlen (key)); 
    Database file encryption NSLog (@ "\n=== database open or create successful ===\n"); 
  Returnyes; 
  }else{NSLog (@ "\n=== database open failed ===\n"); 
 } return NO; 
}-(void) closeDataBase {sqlite3_close (_database); }-(NSString *) DataFilePath: (NSString *) fileName {nsarray *paths =nssearchpathfordirectoriesindomains (NSDocumentDir 
  Ectory, Nsuserdomainmask, YES); 
  NSString *documentsdirectory = [pathsobjectatindex:0]; 
return [Documentsdirectorystringbyappendingpathcomponent:filename]; }-(BOOL) Insertorupdatedata: (NSString *) SQL {if ([selfopendatabase]) {if (Sqlite3_exec _database, [sqlutf8str 
      Ing],nil, &_statement, &_errmsg)!=sqlite_ok) {NSLog (@ "\n=== Insert data failed ===\n"); 
      NSLog (@ "\n==sql error:%s", _errmsg); 
    Returnno; 
      }else{NSLog (@ "\n=== Insert data successfully ===\n"); 
    Returnyes; 
  } sqlite3_close (_database); 
return NO; 
  }-(Nsmutablearray *) seedatabase {Nsmutablearray *users = [[Nsmutablearrayalloc]init]; 
  NSString *sql = [nsstringstringwithformat:@ "SELECT * from t_relive"]; if ([SelfopenDatabase] {if (SQLITE3_PREPARE_V2 (_database, [sqlutf8string],-1, &_statement,nil) ==SQLITE_OK) {while (Sqlite3_step (_statement) ==sqlite_row) 
        {//User *user = [[Question alloc] init]; 
int name =sqlite3_column_int (_statement,0); 
        [user setname:[nsstring stringwithutf8string:name]]; 
int index =sqlite3_column_int (_statement,1); 
[User setid:[[nsstring Stringwithutf8string:index] intvalue]]; 
        [Users Addobject:user]; 
      NSLog (@ "%i=%i", Name,index); 
    } sqlite3_finalize (_statement); 
  } sqlite3_close (_database); 
return to users; 
  }-(int) getcountofdatabase {int count = 0; 
  NSString *sql = [nsstringstringwithformat:@ "SELECT * from User"]; 
      if ([Selfopendatabase]) {if (Sqlite3_prepare_v2 (_database, [sqlutf8string],-1, &_statement,nil) ==SQLITE_OK) { 
      while (Sqlite3_step (_statement) ==sqlite_row) {count + +; } sqlite3_finalize (_statement);
    } return count; @end/////////////////////////////////////////////////////////////////here to implement the input SQL table build database, you can check the console error #import "Appdeleg Ate.h "#import" SqliteHelp.h "@implementation appdelegate-(void) applicationdidfinishlaunching: (Nsnotification *) 
  anotification {//Insert code here to initialize your application [selfbuilddatabase]; 
[Selfinsertdatabase]; 
  }-(void) builddatabase {nserror *error; NSString *textfile = [nsstringstringwithcontentsoffile:[[nsbundlemainbundle]pathforresource:@] 
  Schema.sqlite.tables.sql "oftype:nil]encoding:nsutf8stringencodingerror:&error]; 
  if (Textfile ==nil) {NSLog (@ "Error reading text file.%@", [Errorlocalizedfailurereason]); 
  } nsarray *row = [textfilecomponentsseparatedbystring:@ ";"]; 
  Nsinteger count = [rowcount]; 
  Sqlitehelp *t = [Sqlitehelpnew]; 
    for (int i=0; i<count; i++) {nsstring *tempstring = [nsstringstringwithformat:@ "%@;", Row[i]]; 
    NSLog (@ "%@", tempstring); [TinsErtorupdatedata:tempstring]; 
  }-(void) insertdatabase {nserror *error; NSString *textfile = [nsstringstringwithcontentsoffile:[[nsbundlemainbundle]pathforresource:@] 
  Schema.sqlite.data.sql "oftype:nil]encoding:nsutf8stringencodingerror:&error]; 
  if (Textfile ==nil) {NSLog (@ "Error reading text file.%@", [Errorlocalizedfailurereason]); 
  } nsarray *row = [textfilecomponentsseparatedbystring:@ ";"]; 
  Nsinteger count = [rowcount]; 
  Sqlitehelp *t = [Sqlitehelpnew]; 
    for (int i=0; i<count; i++) {nsstring *tempstring = [nsstringstringwithformat:@ "%@;", Row[i]]; 
    NSLog (@ "%@", tempstring); 
  [Tinsertorupdatedata:tempstring]; 

 }} @end

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

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.