IOS SQLite Encryption Sqlcipher

Source: Internet
Author: User
Tags sqlite format 3

As for Sqlcipher, I will not say more, Baidu a bit, you know. The company's iOS app to give SQLite, today on the internet to look up some information, did the next finishing, the main reference Sqlcipher official integration documents, there is something wrong with everyone put forward to me to improve, thanks to shoot bricks. Official Integration Documentation: https://www.zetetic.net/sqlcipher/ios-tutorial/.

Prerequisites

Install the Xcode development environment, don't say more.

Openssl

This tutorial is provided by Apple Framework:commoncrypto, can be added in engineering, target,build phases, Link Binary, search Commoncrypto can be added.

SQLCipher

Open the terminal and cut to the root of the project you want to integrate Sqlcipher, execute the next command. Download Sqlcipher from GitHub to Local:

$ cd ~/documents/code/Sqlcipherapp$ git clone https://github.com/sqlcipher/sqlcipher.git
Xcode Project Configuration

The SQLCipher source provides a sqlcipher.xcodeproj project file that we'll add to your project to build a static library that's you ll Li NK from your main application target.

ADD Project Reference

Select your project, right-click, select "Add Files to [your project]"; In the pop-up selection window, find the Sqlcipher path you just downloaded from git, open the Sqlcipher folder, select Sqlcipher.xcodeproj;

Note: Do not tick the Copy items if needed check box.

Configure Target Dependencies and Link Binary with Libraries

Click Project, select Targets in your project, click Build phases tab bar.

1. Expand Target Dependencies , add + sqlcipher Static Library

2. Expand Link Binary with Libraries, add +libsqlcipher.a Library

Note: If you have added libsqlite3.dylib or other SQLite libraries in your project library, remove them, or you may be prompted to repeat the SQLite library.

Repeat these steps in the other target of your project.

Configure Build Settings

Go back to your Engineering edit panel, select Project, TARGETS "your project target,Build Settings tab Bar,

1. Select the Header Search Paths Entry and double-click to type the new value:./sqlcipher/src.

Note Fill in the path ... /indicates parent folder

2. Select Other C Flags and double-click Add -dsqlite_has_codec. Note that the release and debug configuration values are the same as:

Note (Translate it yourself): HotTip: The handling of architectures and the meaning of the $(STANDARD_ARCHS) build variable changes Dependin G on the Xcode release, but currently on IOS in Xcode 6.1.1 the armv7s architecture is not included in your build. SQLCipher supports this architecture! If you need to squeeze this much more speed out of SQLCipher on those devices, add the armv7s architecture string to your architectures option in the Build Settings (sample image here).

Integration Code

So far, Sqlcipher has been included in our project, and now we can use Sqlcipher to create or open an encrypted SQLite library. Next Open the program's proxy class, introduce the sqlite3.h header file, find the -applicationdidfinishlaunching:withoptions: proxy method, start the setup code as follows:

////APPDELEGATE.M//securelogindelegate////Created by Billy Gray on 10/19/14.//Copyright (c) zetetic. All rights reserved.// #import "AppDelegate.h"#import<sqlite3.h>@interfaceappdelegate () @property (nonatomic) BOOL isloginviewcontrollerdisplayed; @property (ReadOnly) Nsurl *Databaseurl; @property (ReadOnly) BOOL databaseexists;@end @implementationappdelegate@dynamic databaseurl; @dynamic databaseexists;-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (Nsdictionary *) launchoptions {//Set up the window with Loginviewcontroller as the Rootviewcontroller for now//To avoid showing app view on launch on IOS 8[[Self window] setRootViewController:self.loginViewController];    [[Self window] makekeyandvisible]; Self.isloginviewcontrollerdisplayed=YES; //Set up a SQLCipher database connection:Sqlite3 *DB; if(Sqlite3_open ([[Self.databaseurl Path] utf8string], &db) = =SQLITE_OK) {        Const Char* key = [@"StrongPassword"utf8string]; Sqlite3_key (DB, Key, (int) strlen (key)); if(Sqlite3_exec (DB, (Const Char*)"SELECT Count (*) from Sqlite_master;", NULL, NULL, NULL) = =SQLITE_OK) {NSLog (@"Password is correct, or a new database has been initialized"); } Else{NSLog (@"Incorrect password!");    } sqlite3_close (db); }    returnYES;} -(Nsurl *) Databaseurl {Nsarray*urls =[[Nsfilemanager Defaultmanager] urlsfordirectory:nsdocumentdirectory Indomains:nsuserdomainmask]; Nsurl*directoryurl =[URLs Firstobject]; Nsurl*databaseurl = [Directoryurl urlbyappendingpathcomponent:@"secure.db"]; returnDatabaseurl;} -(BOOL) databaseexists {BOOL exists=NO; Nserror*error =Nil; Exists= [[Self Databaseurl] checkresourceisreachableandreturnerror:&ERROR]; if(exists = = NO && Error! =Nil) {NSLog (@"Error checking availability of database file:%@", error); }    returnexists;}@end

SECURELOGINDELEGATE-APPDELEGATE.M hosted with? by GitHub

OK, compile run your app, configure good words will be able to run successfully, in the console if you can see print the following log content:

While we recommend that you use sqlite3_bind_* the API to avoid some pitfalls, you can also execute as PRAGMA key = ‘some key‘; SQL.

Here are some English to see for yourself:

The call to Sqlite3_key or "PRAGMA key" should occur as the first operation after opening the database. In most cases SQLCipher uses PBKDF2, a salted and iterated key derivation function, to obtain the encryption key. Alternately, an application can-tell SQLCipher-use a specific binary key in BLOB notation (note that SQLCipher requires Exactly-bits of key material), for example:

PRAGMA key = "x ' 2dd29ca851e7b56e4697b0e1f08507293d761a05ce4d1b628663f411a8086d99 '";

Once The key is set SQLCipher would automatically encrypt all data in the database! Note If you don't set a key then SQLCipher'll operate identically to a standard SQLite database.

After the application are wired up to use SQLCipher, take a peek at the resulting data files to make sure everything are In order. An ordinary SQLite database would look something like the following under Hexdump. Note that the file type, schema, and data is clearly readable.

% hexdump-c Plaintext.db 00000000 4c 6f 6d 61 74 20 33 00 | SQLite format 3.| 00000010 04 00 01 01 00 40 20 20 00 00 00 04 00 00 00 00 | [Email protected] ... | ... 000003b0 (XX)--------------------6c |....$ ... 5TABL|000003C0-A-si-a-si-si-si-si-si-|et2t2. CREATE Tab|000003d0 4c 2c 62 29 24 01 06 17 11 11 | LE T2 (A, b) $.....| 000003E0 6c 65 74 31 74 31 02 43 52 45 41 |. 5tablet1t1. CREA|000003F0, 4c, 2c |te TABLE T1 (A, A, b) | ... 000007d0 (77 15 01), 2d, 6f, 6f, |.......-.two for|000007e0, and more. 2f 6f | The show..../.o|000007f0 6e, 6f, 6d, 6f 6e, |ne for the money| 

Fire up the SQLCipher application in simulator and look for the application database files under /USERS/BILLY/LIBR Ary/developer/coresimulator/devices/<some ID number>/data/containers/data/application/<some ID NUMBER> /documents (step through the code in the debugger and enter  po [self.databaseurl Path]  for t He exact path). Try running Hexdump on the application database. With SQLCipher the output should looks completely random, with no discerning characteristics at all.

% hexdump-c Sqlcipher.db 00000000  1b 3c E3 AA, AE, 6d, F6, +  a6 ae  |. 1<, .... q.9m..! c...| 00000010  ca 3e f5 a5 e5  B3 [2e]  : 5a |. P.> 2g .... z|00000020  D8-Eb,  A7 5e, d4 d1  |4.e .... g.^#!!.. | ... 000007d0  af E8 ea 0d 4f $ fe  B7 C2 94 7b EE CA 0b  | ...!.. Od..... {...| 000007E0  8b 1d E9  d4 3c (FC AA  ) d2 |). R..! ... <...d.u|000007f0  d5 E9 3f A9 c5 4b CB------  0a  .... k%.......| 00000800
See Also

All applications this make use of cryptography, including those that use SQLCipher or IOS internal libraries like COMMONCR Ypto and Keychain, must provide documentation to Apple, demonstrates review by the Department of Commerce (DOC) Bureau of industry and Security (BIS) and classification of the application a mass market encryption item.

Information on the PBKDF2 key derivation function was available at http://en.wikipedia.org/wiki/PBKDF2

IOS SQLite Encryption 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.