您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 程式設計技術

用 DES 算法給 SQLite 數據加密:加密存儲與讀取解密的完整實作

編輯:iOS 程式設計技術

涉及的三個知識點

  1. DES 對稱加密算法;
  2. Objective-C 對 SQLite 數據庫的讀寫;
  3. iOS App 中文件存儲的兩種位置及其讀取差異。

一、DES 算法要點

DES 把 64 位的明文塊轉換為 64 位的密文塊,密鑰長度同樣是 64 位。它的做法是按位重新組合輸入數據,並把輸出拆成 L0、R0 兩部分,各 32 位。初始置換規則如下:

58,50,12,34,26,18,10,2,60,52,44,36,28,20,12,4,
62,54,46,38,30,22,14,6,64,56,48,40,32,24,16,8,
57,49,41,33,25,17, 9,1,59,51,43,35,27,19,11,3,
61,53,45,37,29,21,13,5,63,55,47,39,31,23,15,7,

也就是把輸入的第 58 位換到第 1 位,第 50 位換到第 2 位,依此類推,最後一位是原來的第 7 位。置換後的左 32 位是 L0,右 32 位是 R0。若置換前輸入為 D1D2D3……D64,則結果為 L0 = D58D50……D8,R0 = D57D49……D7。

經過 16 輪迭代後得到 L16、R16,把它們作為輸入做逆置換,即得到密文輸出。逆置換正好是初始置換的逆運算——比如第 1 位在初始置換後跑到了第 40 位,逆置換又會把第 40 位換回第 1 位。逆置換規則如下:

40,8,48,16,56,24,64,32,39,7,47,15,55,23,63,31,
38,6,46,14,54,22,62,30,37,5,45,13,53,21,61,29,
36,4,44,12,52,20,60,28,35,3,43,11,51,19,59,27,
34,2,42,10,50,18,58,26,33,1,41, 9,49,17,57,25,

還有兩張常用表。放大置換表(E 盒):

32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9,10,11,
12,13,12,13,14,15,16,17,16,17,18,19,20,21,20,21,
22,23,24,25,24,25,26,27,28,29,28,29,30,31,32, 1,

單純置換表(P 盒):

16, 7,20,21,29,12,28,17, 1,15,23,26, 5,18,31,10,
 2, 8,24,14,32,27, 3, 9,19,13,30, 6,22,11, 4,25,

在 f(Ri, Ki) 的計算中,S1 到 S8 是選擇函數,作用是把 6 bit 數據壓縮為 4 bit。八個 S 盒的功能表如下:

S1:
14, 4,13, 1, 2,15,11, 8, 3,10, 6,12, 5, 9, 0, 7,
 0,15, 7, 4,14, 2,13, 1,10, 6,12,11, 9, 5, 3, 8,
 4, 1,14, 8,13, 6, 2,11,15,12, 9, 7, 3,10, 5, 0,
15,12, 8, 2, 4, 9, 1, 7, 5,11, 3,14,10, 0, 6,13,

S2:
15, 1, 8,14, 6,11, 3, 4, 9, 7, 2,13,12, 0, 5,10,
 3,13, 4, 7,15, 2, 8,14,12, 0, 1,10, 6, 9,11, 5,
 0,14, 7,11,10, 4,13, 1, 5, 8,12, 6, 9, 3, 2,15,
13, 8,10, 1, 3,15, 4, 2,11, 6, 7,12, 0, 5,14, 9,

S3:
10, 0, 9,14, 6, 3,15, 5, 1,13,12, 7,11, 4, 2, 8,
13, 7, 0, 9, 3, 4, 6,10, 2, 8, 5,14,12,11,15, 1,
13, 6, 4, 9, 8,15, 3, 0,11, 1, 2,12, 5,10,14, 7,
 1,10,13, 0, 6, 9, 8, 7, 4,15,14, 3,11, 5, 2,12,

S4:
 7,13,14, 3, 0, 6, 9,10, 1, 2, 8, 5,11,12, 4,15,
13, 8,11, 5, 6,15, 0, 3, 4, 7, 2,12, 1,10,14, 9,
10, 6, 9, 0,12,11, 7,13,15, 1, 3,14, 5, 2, 8, 4,
 3,15, 0, 6,10, 1,13, 8, 9, 4, 5,11,12, 7, 2,14,

S5:
 2,12, 4, 1, 7,10,11, 6, 8, 5, 3,15,13, 0,14, 9,
14,11, 2,12, 4, 7,13, 1, 5, 0,15,10, 3, 9, 8, 6,
 4, 2, 1,11,10,13, 7, 8,15, 9,12, 5, 6, 3, 0,14,
11, 8,12, 7, 1,14, 2,13, 6,15, 0, 9,10, 4, 5, 3,

S6:
12, 1,10,15, 9, 2, 6, 8, 0,13, 3, 4,14, 7, 5,11,
10,15, 4, 2, 7,12, 9, 5, 6, 1,13,14, 0,11, 3, 8,
 9,14,15, 5, 2, 8,12, 3, 7, 0, 4,10, 1,13,11, 6,
 4, 3, 2,12, 9, 5,15,10,11,14, 1, 7, 6, 0, 8,13,

S7:
 4,11, 2,14,15, 0, 8,13, 3,12, 9, 7, 5,10, 6, 1,
13, 0,11, 7, 4, 9, 1,10,14, 3, 5,12, 2,15, 8, 6,
 1, 4,11,13,12, 3, 7,14,10,15, 6, 8, 0, 5, 9, 2,
 6,11,13, 8, 1, 4,10, 7, 9, 5, 0,15,14, 2, 3,12,

S8:
13, 2, 8, 4, 6,15,11, 1,10, 9, 3,14, 5, 0,12, 7,
 1,15,13, 8,10, 3, 7, 4,12, 5, 6,11, 0,14, 9, 2,
 7,11, 4, 1, 9,12,14, 2, 0, 6,10,13,15, 3, 5, 8,
 2, 1,14, 7, 4,10, 8,13,15,12, 9, 0, 3, 5, 6,11,

以 S1 為例:它有 4 行(0~3 行)、16 列(0~15 列)。設輸入為 D = D1D2D3D4D5D6,則列 = D2D3D4D5,行 = D1D6,在表中查得對應數值並以 4 位二進制表示,即為 S1 的輸出。

子密鑰 Ki(48 bit)的生成:初始 Key 為 64 位,但其中第 8、16、……、64 位是奇偶校驗位,不參與運算,所以真正可用的只有 56 位。經過置換表 1 的壓縮後,Key 由 64 位變成 56 位,拆分為 C0、D0 各 28 位;分別循環左移得到 C1、D1,合併成 56 位後再走一次置換表 2,便得到 48 位的 K0。依此類推得到 K1 到 K15,其中 16 輪的循環左移位數依次為:

1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1

DES 的解密過程與加密完全相同,唯一區別是子密鑰的使用順序顛倒:第一次迭代用 K15,第二次用 K14,……,最後一次用 K0,算法本身不做任何改動。

DES 的安全性相當高,除了窮舉搜索之外,目前還沒有更有效的破譯手段。56 位密鑰的窮舉空間是 2 的 56 次方,即便一台機器每秒能嘗試一百萬個密鑰,全部跑完也需要上千年,實際上很難實現。當然,隨着算力增長,若追求更高強度的保護,可以考慮改用密鑰更長的算法。

二、OC 操作 SQLite

數據庫的讀寫通常包括創建、打開、增刪改查與關閉。OC 中這些操作本質上就是把 SQL 語句包成字符串交給數據庫執行,具體見下面的代碼。

三、iOS 中文件存儲的兩種位置

App 中的數據與文件有兩種放法:

  • 應用包(bundle)內部:與頭文件、.m 文件同一棵樹。只能讀,不能寫;
  • 沙盒(Sandbox):可讀可寫。

因此凡是用戶會修改、或應用使用過程中會變動的內容,都應該放進沙盒。兩種位置的讀取方式代碼中都有體現。

四、完整實作:加密存儲 + 讀取解密

下面的代碼實現的功能是:從應用的 bundle 中讀取原始 SQLite 數據庫,除 id 和 use 兩個字段外,其餘字段全部用 DES 加密,再按原有表結構寫入沙盒中新建的數據庫。之後需要讀取時,先按 id 或 use 定位記錄,再對其他字段解密。

#import "ViewController.h"
#import "jiami.h"
#import "FMDatabase.h"

@interface ViewController () {
    FMDatabase *mydb;     // 沙盒中的目標庫(存放加密數據)
    FMDatabase *mydbins;  // bundle 中的源庫(明文數據)
    NSString *key;
    jiami *secret;
    UIButton *myBtn;
    UITextField *textField;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    key = @"secret";
    secret = [[jiami alloc] init];

    // 讀取 bundle 中的源數據庫
    NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"meridianPoint" ofType:@"sqlite"];
    mydbins = [[FMDatabase alloc] initWithPath:bundlePath];

    // 在沙盒中準備目標數據庫
    NSString *documentsPath = [NSHomeDirectory() stringByAppendingString:@"/Documents/mydb.sqlite"];
    mydb = [[FMDatabase alloc] initWithPath:documentsPath];

    // 建表語句,結構與源表保持一致
    NSString *tablecreate = @"create table if not exists mytable("
        "id text primary key, meridian_id text, name text, property1_id text, "
        "property2_id text, property3_id text, use text, position text, "
        "dissection text, indications text, synergy text, acupuncture text, "
        "note text, x text, y text, dict text, py_name text, "
        "meridian_text text, GB text)";

    if ([mydb open]) {
        BOOL yesOrNo = [mydb executeUpdate:tablecreate];
        NSLog(yesOrNo ? @"建表成功" : @"建表失敗");
        [mydb close];
    }

    // 同時打開兩個庫開始搬運
    if ([mydbins open] && [mydb open]) {
        for (int i = 0; i < 363; i++) {
            NSString *sqlString = [NSString stringWithFormat:@"select * from acupoint_cn where id = %d", i];
            FMResultSet *result = [mydbins executeQuery:sqlString];
            while ([result next]) {
                NSString *idd            = [result stringForColumn:@"id"];
                NSString *meridian_idd   = [result stringForColumn:@"meridian_id"];
                NSString *named          = [result stringForColumn:@"name"];
                NSString *property1_idd  = [result stringForColumn:@"property1_id"];
                NSString *property2_idd  = [result stringForColumn:@"property2_id"];
                NSString *property3_idd  = [result stringForColumn:@"property3_id"];
                NSString *positiond      = [result stringForColumn:@"position"];
                NSString *use            = [result stringForColumn:@"use"];
                NSString *dissectiond    = [result stringForColumn:@"dissection"];
                NSString *indicationsd   = [result stringForColumn:@"indications"];
                NSString *synergyd       = [result stringForColumn:@"synergy"];
                NSString *acupunctured   = [result stringForColumn:@"acupuncture"];
                NSString *xd             = [result stringForColumn:@"x"];
                NSString *yd             = [result stringForColumn:@"y"];
                NSString *noted          = [result stringForColumn:@"note"];
                NSString *py_named       = [result stringForColumn:@"py_name"];
                NSString *dictd          = [result stringForColumn:@"dict"];
                NSString *meridian_textd = [result stringForColumn:@"meridian_text"];
                NSString *GBd            = [result stringForColumn:@"GB"];

                // 除 id 和 use 之外的字段全部加密
                NSString *meridian_id   = [secret encryptUseDES:meridian_idd key:key];
                NSString *name          = [secret encryptUseDES:named key:key];
                NSString *property1_id  = [secret encryptUseDES:property1_idd key:key];
                NSString *property2_id  = [secret encryptUseDES:property2_idd key:key];
                NSString *property3_id  = [secret encryptUseDES:property3_idd key:key];
                NSString *position      = [secret encryptUseDES:positiond key:key];
                NSString *dissection    = [secret encryptUseDES:dissectiond key:key];
                NSString *indications   = [secret encryptUseDES:indicationsd key:key];
                NSString *synergy       = [secret encryptUseDES:synergyd key:key];
                NSString *acupuncture   = [secret encryptUseDES:acupunctured key:key];
                NSString *x             = [secret encryptUseDES:xd key:key];
                NSString *y             = [secret encryptUseDES:yd key:key];
                NSString *note          = [secret encryptUseDES:noted key:key];
                NSString *py_name       = [secret encryptUseDES:py_named key:key];
                NSString *dict          = [secret encryptUseDES:dictd key:key];
                NSString *meridian_text = [secret encryptUseDES:meridian_textd key:key];
                NSString *GB            = [secret encryptUseDES:GBd key:key];

                // 寫入沙盒數據庫
                [mydb executeUpdate:@"insert into mytable(id, meridian_id, name, property1_id, "
                    "property2_id, property3_id, use, position, dissection, indications, "
                    "synergy, acupuncture, note, x, y, dict, py_name, meridian_text, GB) "
                    "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
                    idd, meridian_id, name, property1_id, property2_id, property3_id, use,
                    position, dissection, indications, synergy, acupuncture, note, x, y,
                    dict, py_name, meridian_text, GB];
            }
        }
        [mydbins close];
        [mydb close];
    }

    // 一個簡單的按鈕與輸入框,用來驗證效果
    myBtn = [[UIButton alloc] initWithFrame:CGRectMake(150, 300, 114, 50)];
    myBtn.backgroundColor = [UIColor orangeColor];
    myBtn.layer.cornerRadius = 20;
    myBtn.layer.masksToBounds = YES;
    myBtn.enabled = YES;
    [myBtn setTitle:@"開始按鈕" forState:UIControlStateNormal];
    [myBtn addTarget:self action:@selector(myBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:myBtn];

    textField = [[UITextField alloc] initWithFrame:CGRectMake(100, 100, 214, 100)];
    [textField setBackgroundColor:[UIColor lightGrayColor]];
    textField.placeholder = @"請輸入要查詢的病症";
    [self.view addSubview:textField];
}

// 點擊按鈕進行查詢(此功能尚未完善)
- (void)myBtnAction:(UIButton *)sender {
    if ([mydb open]) {
        FMResultSet *result = [mydb executeQuery:@"select * from mytable where use like ?",
                               textField.text];
        while ([result next]) {
            NSString *use = [result stringForColumn:@"use"];
            // 需要展示明文時,在這裡解密
            // NSString *useunsecret = [secret decryptUseDES:use key:key];
            textField.text = use;
        }
        [mydb close];
    }
}

// 點擊空白處收起鍵盤
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [textField resignFirstResponder];
}
@end

五、需要注意的地方

1. 打開與關閉要成對出現,並用 if 判斷是否打開成功,失敗時打印原因:

if ([數據庫名 open]) {
    操作語句;
    // ...
    [數據庫名 close];
} else {
    NSLog(@"數據庫未能打開");
}

2. 查詢結果是集合,必須靠 next 逐行取值,想取哪個字段就換掉 stringForColumn: 的參數:

NSString *sqlString = [NSString stringWithFormat:@"select * from acupoint_cn where id = %d", i];
FMResultSet *result = [mydbins executeQuery:sqlString];
while ([result next]) {
    NSString *idd = [result stringForColumn:@"id"];
}

3. 建議先把 SQL 拼成字符串再傳參。直接把語句寫進 executeQuery 也不是不行,但當語句裡有變量(比如 for 循環的 i)需要拼接時,先構造字符串更清晰、也更不容易出錯。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved