天天看點

安卓設定keychain_KeyChainWrapper - keychain簡單使用

#import

@interfaceFFKeyChain : NSObject+ (void)save:(NSString *)serve data:(id)Data;+ (id)read:(NSString *)serve;@end

#import "FFKeyChain.h"

@implementationFFKeyChain

+ (NSMutableDictionary *)getKeyChainQuery:(NSString *)serve {return [@{(id)kSecClass:(id)kSecClassGenericPassword,

(id)kSecAttrAccount:serve,

(id)kSecAttrService:serve,

(__bridge NSString*)kSecAttrAccessible:(__bridge NSString *)kSecAttrAccessibleAfterFirstUnlock,

} mutableCopy];

}+(NSMutableDictionary*)keyChainIdentifier:(NSString*)identifier {

NSMutableDictionary* keyChainMutableDictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:(id)kSecClassGenericPassword,kSecClass,identifier,kSecAttrService,identifier,kSecAttrAccount,kSecAttrAccessibleAfterFirstUnlock,kSecAttrAccessible, nil];returnkeyChainMutableDictionary;

}+ (void)save:(NSString *)serve data:(id)Data {

NSMutableDictionary*mDic = [self keyChainIdentifier:serve];//[self getKeyChainQuery:serve];//;

SecItemDelete((CFDictionaryRef)mDic);

[mDic setObject:[NSKeyedArchiver archivedDataWithRootObject:Data] forKey:(id)kSecValueData];

OSStatus sta=SecItemAdd((__bridge CFDictionaryRef)mDic, NULL);if (sta ==noErr) {

NSLog(@"成功。。");

};

}+ (void)delete:(NSString *)serve {

NSMutableDictionary*mdic =[self getKeyChainQuery:serve];

SecItemDelete((__bridge CFDictionaryRef)mdic);

}

+ (void)neeUpdateServe:(NSString *)server updateValue:(NSString *)value {

NSMutableDictionary *mdic = [self getKeyChainQuery:server];

OSStatus status = SecItemUpdate((__bridge CFDictionaryRef)mdic, (__bridge CFDictionaryRef)@{(id)kSecValueData:[NSKeyedArchiver archivedDataWithRootObject:value]});

if (status == errSecSuccess) {

NSLog(@"更新成功");

}else {

NSLog(@"更新失敗");

}

}+ (id)read:(NSString *)serve {id let =nil;

NSMutableDictionary*mdic =[self getKeyChainQuery:serve];

[mdic setValue:(id)kCFBooleanTrue forKey:(id)kSecReturnData];

[mdic setValue:(id)kSecMatchLimitOne forKey:(id)kSecMatchLimit];

CFDataRef keyData=nil;if (SecItemCopyMatching((__bridge CFDictionaryRef)mdic, (CFTypeRef *)&keyData) ==noErr) {@try{

let= [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData *)keyData];

}@catch (NSException *e) {

NSLog(@"Unarchiver of %@ failed %@", serve, e);

}@finally{

}

}if(keyData) {

CFRelease(keyData);

}returnlet;

}@end