YostarKeychain.m 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. //
  2. // YostarKeychain.m
  3. // YostarUtilits
  4. //
  5. // Created by Yostar on 2018/6/21.
  6. // Copyright © 2018年 Yostar. All rights reserved.
  7. //
  8. #import "YostarKeychain.h"
  9. #import <Security/Security.h>
  10. @implementation YostarKeychain
  11. + (NSMutableDictionary *)getKeychainQuery:(NSString *)service{
  12. return [NSMutableDictionary dictionaryWithObjectsAndKeys:
  13. (id)kSecClassGenericPassword, (id)kSecClass,
  14. service, (id)kSecAttrService,
  15. service, (id)kSecAttrAccount,
  16. (id)kSecAttrAccessibleAfterFirstUnlock, (id)kSecAttrAccessible, nil];
  17. }
  18. #pragma mark - 写入
  19. + (void)save:(NSString *)service data:(id)data{
  20. //Get search dictionary
  21. NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
  22. //Delete old item before add new item
  23. SecItemDelete((CFDictionaryRef)keychainQuery);
  24. //Add new object to search dictionary(Attention:the data format)
  25. [keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:data] forKey:(id)kSecValueData];
  26. //Add item to keychain with the search dictionary
  27. SecItemAdd((CFDictionaryRef)keychainQuery, NULL);
  28. }
  29. #pragma mark - 读取
  30. + (id)load:(NSString *)service{
  31. id result = nil;
  32. NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
  33. //Configure the search setting
  34. //Since in our simple case we are expecting only a single attribute to be returned (the password) we can set the attribute kSecReturnData to kCFBooleanTrue
  35. [keychainQuery setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnData];
  36. [keychainQuery setObject:(id)kSecMatchLimitOne forKey:(id)kSecMatchLimit];
  37. CFDataRef keyData = NULL;
  38. if (SecItemCopyMatching((CFDictionaryRef)keychainQuery, (CFTypeRef *)&keyData) == noErr) {
  39. @try {
  40. result = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData *)keyData];
  41. // result = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge_transfer NSData *)keyData];
  42. } @catch (NSException *exception) {
  43. NSLog(@"Unarchive of %@ failed: %@", service, exception);
  44. } @finally {
  45. }
  46. }
  47. if (keyData) {
  48. CFRelease(keyData);
  49. }
  50. return result;
  51. }
  52. #pragma mark - 删除
  53. + (void)delete:(NSString *)service{
  54. NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
  55. SecItemDelete((CFDictionaryRef)keychainQuery);
  56. }
  57. @end