使用FMDB加密数据库的错误尝试

在公司产品上线前, 准备把数据库加密掉, 本来是几行代码的事情, 倒腾了几个小时......

1. 加密操作

网上大多数方法的做法是, 直接修改FMDatabase.h方法, 我认为直接修改第三方库的源码, 是不科学的, 我的做法是创建新类, 继承自FMDatabase, 重写相应的方法, 在需要加密的地方, 添加加密用的语句.

2. 错误方式

原来项目中已经通过cocoapod集成了FMDB 框架. 刚开始我的做法是, 在Profile上直接加上pod 'FMDB/SQLCipher' #数据库加密, 这时候Profile中同时包含 pod 'FMDB' #数据库`` pod 'FMDB/SQLCipher', 安装之后, 不管怎么测试, 总是无法读写数据库, 耗了好长时间, 最终发现, 删除 ``pod 'FMDB'` 之后, 就可以正常读写了......

cocoapod集成SQLCipher时候, Profile加入 'FMDB/SQLCipher' 即可!!

3. 为了实现加密重写的方法

#pragma mark - 对FMDataBase加密, 使用 SQLCipher, 通过重载方法 实现加密
#import "sqlite3.h"

@implementation FMCipherDataBase

static NSString *DB_SECRETKEY = @"123456";


+ (instancetype)databaseWithPath:(NSString *)inPath cipherKey:(NSString *)cipherKey {
    
    FMCipherDataBase *database = [super databaseWithPath:inPath];
    DB_SECRETKEY = cipherKey;
    return database;
}

- (const char*)sqlitePath {
    
    if (!_databasePath) {
        return ":memory:";
    }
    
    if ([_databasePath length] == 0) {
        return ""; // this creates a temporary database (it's an sqlite thing).
    }
    
    return [_databasePath fileSystemRepresentation];
    
}

- (BOOL)open {
    if (_db) {
        return YES;
    }
    
    int err = sqlite3_open([self sqlitePath], (sqlite3**)&_db );
    if(err != SQLITE_OK) {
        NSLog(@"error opening!: %d", err);
        return NO;
    } else {
        
        [self setKey:DB_SECRETKEY];
    }
    
    if (_maxBusyRetryTimeInterval > 0.0) {
        // set the handler
        [self setMaxBusyRetryTimeInterval:_maxBusyRetryTimeInterval];
    }
    
    
    return YES;
}

- (BOOL)openWithFlags:(int)flags vfs:(NSString *)vfsName {
#if SQLITE_VERSION_NUMBER >= 3005000
    if (_db) {
        return YES;
    }
    
    int err = sqlite3_open_v2([self sqlitePath], (sqlite3**)&_db, flags, [vfsName UTF8String]);
    if(err != SQLITE_OK) {
        NSLog(@"error opening!: %d", err);
        return NO;
    } else {
        
        [self setKey:DB_SECRETKEY];
    }
    
    if (_maxBusyRetryTimeInterval > 0.0) {
        // set the handler
        [self setMaxBusyRetryTimeInterval:_maxBusyRetryTimeInterval];
    }
    
    return YES;
#else
    NSLog(@"openWithFlags requires SQLite 3.5");
    return NO;
#endif
}

@end

详情请参考: https://github.com/hell03W/FMDBHelper

转载于:https://my.oschina.net/whforever/blog/780657

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值