您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

使用 Keychain 的 kSecClassGenericPassword 保存敏感資料

編輯:iOS 開發綜合

Keychain 的特性

iOS 的 Keychain 是一個安全的儲存容器,常用來保存帳號、密碼、認證 token 等敏感資訊。Keychain 內的資料會加密保存,即使 App 被刪除,部分資料仍可能保留,重新安裝後仍可讀取。

若要使用 Keychain,需要在 Build Phases 中加入 Security.framework。

自封裝保存方式

若只需要保存簡單物件,可以自己封裝一個工具類。概念是將資料轉成 NSData,再以 kSecClassGenericPassword 存入 Keychain。

+ (NSMutableDictionary *)getKeychainQuery:(NSString *)service {
    return [NSMutableDictionary dictionaryWithObjectsAndKeys:
        (id)kSecClassGenericPassword, (id)kSecClass,
        service, (id)kSecAttrService,
        service, (id)kSecAttrAccount,
        (id)kSecAttrAccessibleAfterFirstUnlock, (id)kSecAttrAccessible,
        nil
    ];
}

+ (BOOL)save:(NSString *)service data:(id)data {
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
    SecItemDelete((CFDictionaryRef)keychainQuery);

    [keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:data] forKey:(id)kSecValueData];
    return SecItemAdd((CFDictionaryRef)keychainQuery, NULL) == noErr;
}

+ (void)delete:(NSString *)service {
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
    SecItemDelete((CFDictionaryRef)keychainQuery);
}

讀取資料

讀取時,會在查詢字典中加入 kSecReturnData 與 kSecMatchLimitOne,讓 Keychain 回傳一筆符合條件的資料。取得 NSData 後,再用 NSKeyedUnarchiver 還原成原本物件。

常用 API

  • SecItemAdd:新增資料。
  • SecItemUpdate:更新資料。
  • SecItemDelete:刪除資料。
  • SecItemCopyMatching:查詢資料。

模擬器上的觀察

在模擬器上,每次重新執行 App 時,實際上可能會經歷卸載與重新安裝的流程。但存於 Keychain 的資料仍可能保留,因此可用來驗證持久化效果。

使用蘋果官方範例

若需求較複雜,也可以參考 Apple 提供的 KeychainItemWrapper。其原理同樣是透過 SecItemAdd、SecItemUpdate、SecItemDelete、SecItemCopyMatching 操作 Keychain,只是封裝了更多欄位與錯誤處理。

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