变更记录
序号 | 录入时间 | 录入人 | 备注 |
---|---|---|---|
1 | 2016-04-23 | Alfred Jiang | - |
方案名称
数据库 - 使用 SQLCipher 进行数据库加密存储
关键字
数据库 \ SQLCipher \ 加密
需求场景
- 需要对存储于数据库中的数据进行加密时
参考链接
- CSDN - sqlite 数据库加密(SQLCipher)
- CSDN - ios中的SQL数据库文件加密 (使用sqlcipher)
- SQLCipher - Adding SQLCipher to Xcode Projects(推荐)
详细内容
1. 添加
可参考 SQLCipher - Adding SQLCipher to Xcode Projects
2. 使用
参考以下示例
//
// 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...
Bulid Settings -> Architectures和Valid Architectures里面都改成一样(例如:都填写 armv6 armv7)
warning: implicit declaration of function 'sqlite3_key' is invalid in C99
Bulid Settings -> C Language Dialect 改为:C89[-std-c89] 就可以,即使用c89标准
效果图
(无)
备注
(无)