变更记录

序号 录入时间 录入人 备注
1 2016-04-23 Alfred Jiang -

方案名称

数据库 - 使用 SQLCipher 进行数据库加密存储

关键字

数据库 \ SQLCipher \ 加密

需求场景

  1. 需要对存储于数据库中的数据进行加密时

参考链接

  1. CSDN - sqlite 数据库加密(SQLCipher)
  2. CSDN - ios中的SQL数据库文件加密 (使用sqlcipher)
  3. SQLCipher - Adding SQLCipher to Xcode Projects(推荐)

详细内容

1. 添加

可参考 SQLCipher - Adding SQLCipher to Xcode Projects

2. 使用

参考以下示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
//
// AppDelegate.m
// SecureLoginDelegate
//
// Created by Billy Gray on 10/19/14.
// Copyright (c) 2014 Zetetic. All rights reserved.
//

#import "AppDelegate.h"
#import <sqlite3.h>

@interface AppDelegate ()
@property (nonatomic) BOOL isLoginViewControllerDisplayed;
@property (readonly) NSURL *databaseURL;
@property (readonly) BOOL databaseExists;
@end

@implementation AppDelegate
@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);
}
return YES;
}

- (NSURL *)databaseURL {
NSArray *URLs = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
NSURL *directoryURL = [URLs firstObject];
NSURL *databaseURL = [directoryURL URLByAppendingPathComponent:@"secure.db"];
return databaseURL;
}

- (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);
}
return exists;
}

@end
3. 注意事项

若出现以下错误提示:

  • No architectures to compile for (ARCHS=armv6,armv7, VALID_ARCHS=armv7 armv7s…

    1
    Bulid Settings -> Architectures和Valid Architectures里面都改成一样(例如:都填写 armv6 armv7)
  • warning: implicit declaration of function ‘sqlite3_key’ is invalid in C99

    1
    Bulid Settings -> C Language Dialect 改为:C89[-std-c89] 就可以,即使用c89标准  

效果图

(无)

备注

(无)