如何使用ARC在iOS 7中存储密码

时间:2014-06-15 20:37:25

标签: ios objective-c keychain keychainitemwrapper

我正在开发适用于iOS 7的应用,并且正在使用ARC。我正在使用Web服务,因此用户必须使用用户名和密码登录Web服务。我知道只是存储用户名和密码并不好,所以我想使用keychain来存储用户名和密码。

在做了一些研究后,人们似乎建议使用KeychainItemWrapper,但这与ARC不兼容。如何使用ARC在iOS 7中使用钥匙串存储密码?任何帮助和指导将不胜感激。

1 个答案:

答案 0 :(得分:2)

我使用以下内容:

+ (void)keyChainSaveKey:(NSString *)key data:(id)data
{
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:key];
    SecItemDelete((__bridge CFDictionaryRef)keychainQuery);
    [keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:data] forKey:(__bridge id)kSecValueData];
    SecItemAdd((__bridge CFDictionaryRef)keychainQuery, NULL);
}

+ (id)keyChainLoadKey:(NSString *)key
{
    id ret = nil;
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:key];
    [keychainQuery setObject:(id)kCFBooleanTrue forKey:(__bridge id)kSecReturnData];
    [keychainQuery setObject:(__bridge id)kSecMatchLimitOne forKey:(__bridge id)kSecMatchLimit];
    CFDataRef keyData = NULL;
    if (SecItemCopyMatching((__bridge CFDictionaryRef)keychainQuery, (CFTypeRef *)&keyData) == noErr) {
        @try {
            ret = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData *)keyData];
        }
        @catch (NSException *e) {
            //NS Log(@"Unarchive of %@ failed: %@", service, e);
        }
        @finally {}
    }
    if (keyData) CFRelease(keyData);
    return ret;
}

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

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

您可能需要

#import <CommonCrypto/CommonCryptor.h>

我不记得我在哪里找到了这段代码...所以我不能给予信任:(