ios中KeyChain用途(整理) – iPhone手機開發技術文章 iPhone軟體開發教學課程

一、在應用間利用KeyChain共享數據

我們可以把KeyChain理解為一個Dictionary,所有數據都以key-value的形式存儲,可以對這個Dictionary進行add、update、get、delete這四個操作。對於每一個應用來說,KeyChain都有兩個訪問區,私有區和公共區。私有區是一個sandbox,本程序存儲的任何數據都對其他程序不可見。而要想在將存儲的內容放在公共區,需要先聲明公共區的名稱,官方文檔管這個名稱叫“keychain access group”,聲明的方法是新建一個plist文件,名字隨便起,內容如下:
vcq9o6zDv7j2aW9zs8zQ8ra809DSu7j2tsDBorXEa2V5Y2hhaW605rSioaPP4LbU09pOU1VzZXJEZWZhdWx0c6GizsS8/rGjtOa1yNK7sOO3vcq9o6xrZXljaGFpbrGjtOa4/M6qsLLIq6OstvjH0mtleWNoYWluwO+xo7TmtcTQxc+isru74dLyQXBwsbvJvrP9tvi2qsqno6zL+dLU1NrW2NewQXBwuvOjrGtleWNoYWluwO+1xMr9vt27ucTcyrnTw6GjCtTa06bTw8DvyrnTw8q508NrZXlDaGFpbqOsztLDx9Do0qq1vMjrU2VjdXJpdHkuZnJhbWV3b3JrIKOsa2V5Y2hhaW61xLLZ1/e907/ayfnD99TazbfOxLz+U2VjSXRlbS5owO+ho9axvdPKudPDU2VjSXRlbS5owO+3vbeostnX92tleWNoYWluo6zQ6NKq0LS1xLT6wuu9z86quLTU06Oszqq89cfh1NvDx7PM0PLUsbXEv6q3oqOsztLDx7/J0tTKudPD0rvQqdLRvq234tewusPBy7XEuaS+38Dgo6zPwsPmztK74bzytaW96cncz8LO0tPDuf21xMG9uPa5pL7fwOCjuktleWNoYWluSXRlbVdyYXBwZXK6zVNGSEZLZXljaGFpblV0aWxzoaM8YnI+Cjxicj4KCjxzdHJvbmc+o6jSu6OpS2V5Y2hhaW5JdGVtV3JhcHBlcjwvc3Ryb25nPjxicj4Kz8LU2LXY1rejumh0dHA6Ly9kb3dubG9hZC5jc2RuLm5ldC9kZXRhaWwvdTAxMTQzOTY4OS82ODc3NjQxPGJyPgpLZXljaGFpbkl0ZW1XcmFwcGVyysdhcHBsZbnZt73A/dfTobBHZW5lcmljS2V5Y2hhaW6hscDv0ru49rfDzsprZXljaGFpbrOj08Oy2df3tcS34tewwOCjrNTaudnN+MnPz8LU2MHLR2VuZXJpY0tleWNoYWluz+7Ev7rzo6zWu9Do0qqw0aGwS2V5Y2hhaW5JdGVtV3JhcHBlci5oobG6zaGwS2V5Y2hhaW5JdGVtV3JhcHBlci5tobG/vbG0tb3O0sPHz+7Ev6OssqK1vMjrU2VjdXJpdHkuZnJhbWV3b3JrIKGjS2V5Y2hhaW5JdGVtV3JhcHBlcrXE08O3qKO6Ci8qKiCz9cq8u6/Su7j2saO05tPDu6fVyrrFtcRLZXljaGFpbkl0ZW1XcmFwcGVyICovCktleWNoYWluSXRlbVdyYXBwZXIgKndyYXBwZXIgPSBbW0tleWNoYWluSXRlbVdyYXBwZXIgYWxsb2NdIGluaXRXaXRoSWRlbnRpZmllcjpA”Account Number” accessGroup:@”YOUR_APP_ID_HERE.com.yourcompany.AppIdentifier”];

//保存帳號
[wrapper setObject:@”” forKey:(id)kSecAttrAccount];
//保存密碼
[wrapper setObject:@”” forKey:(id)kSecValueData];
//從keychain裡取出帳號密碼
NSString *password = [wrapper objectForKey:(id)kSecValueData];
//清空設置
[wrapper resetKeychainItem];
其中方法“- (void)setObject:(id)inObject forKey:(id)key;”裡參數“forKey”的值應該是Security.framework 裡頭文件“SecItem.h”裡定義好的key,用其他字符串做key程序會崩潰!

(二)SFHFKeychainUtils 提供瞭在 iOS keychain中安全的存儲密碼的工具
下載地址:https://download.csdn.net/detail/u011439689/6877655
1、引入Security.frameWork框架。
2、引入頭文件:SFHKeychainUtils.h.
3、存密碼:
[SFHFKeychainUtils storeUsername:@”dd” andPassword:@”aa”forServiceName:SERVICE_NAME updateExisting:1 error:nil];
[SFHFKeychainUtils deleteItemForUsername:@”dd” andServiceName:SERVICE_NAME error:nil];
4、取密碼:
NSString *passWord = [SFHFKeychainUtils getPasswordForUsername:@”dd”andServiceName:SERVICE_NAME error:nil];

發佈留言