簡體   English   中英

我應該用哪個密鑰在iOS鑰匙串中存儲密碼?

[英]which key should I use to store the password in iOS keychain?

Apple GenericKeychain示例中的KeychainItemWrapper類使用kSecValueData鍵來存儲密碼。

但參考http://developer.apple.com/library/ios/#documentation/Security/Reference/keychainservices/Reference/reference.html#//apple_ref/doc/uid/TP30000898

表示在SecItemCopyMatching或SecItemAdd的結果字典中使用了kSecValueData,表示返回值的類型。

當我調用SecItemAdd來創建鑰匙串項時,我應該使用哪個鍵?

您應該使用kSecValue數據作為密鑰來存儲密碼(以NSData或CFDataRef格式)。

該主題的參考有點不清楚,kSecValueData鍵用作輸出鍵和輸入鍵。 也就是說,在查詢鑰匙串項(SecItemCopyMatching)並指定kSecReturnAttributes鍵時使用它,因此結果作為字典返回,密碼將存儲在該字典的kSecValueData鍵下。 您還可以在將項添加到鑰匙串(SecItemAdd)時使用它,在調用方法之前將密碼的NSData或CFDataRef值存儲在kSecValueData鍵中。

以下是兩種情況的示例:

檢索密碼:

NSMutableDictionary *queryDictionary = [[NSMutableDictionary alloc] init];
[queryDictionary setObject: (__bridge id)kSecClassGenericPassword forKey: (__bridge id<NSCopying>)kSecClass];
[queryDictionary setObject:service forKey:kSecAttrService];
[queryDictionary setObject:account forKey:kSecAttrAccount];
// The result will be a dictionary containing the password attributes...
[queryDictionary setObject:YES forKey:(__bridge id<NSCopying>)(kSecReturnAttributes)];
// ...one of those attributes will be a kSecValueData with the password
[queryDictionary setObject:YES forKey:(__bridge id<NSCopying>)(kSecReturnData)];
OSStatus sanityCheck = SecItemCopyMatching((__bridge CFDictionaryRef)(queryDictionary), (CFTypeRef *)&result);
if (sanityCheck != noErr)
{
    NSDictionary * resultDict = (__bridge NSDictionary *)result;
    // here's the queried password value
    NSData *passwordValue = [resultDict objectForKey:(__bridge id)(kSecValueData)];
}

添加密碼:

NSString *passwordString = @"my password value";
NSData *passwordData = [passwordString dataUsingEncoding:NSUTF8StringEncoding];
CFDictionaryRef result = nil;
NSMutableDictionary *addDictionary = [[NSMutableDictionary alloc] init];
[addDictionary setObject: (__bridge id)kSecClassGenericPassword forKey: (__bridge id<NSCopying>)kSecClass];
[addDictionary setObject:service forKey:kSecAttrService];
[addDictionary setObject:account forKey:kSecAttrAccount];

// here goes the password value
[addDictionary setObject:passwordData forKey:(__bridge id<NSCopying>)(kSecValueData)];

OSStatus sanityCheck = SecItemAdd((__bridge CFDictionaryRef)(queryDictionary), NULL)
if (sanityCheck != noErr)
{
   // if no error the password got successfully stored in the keychain
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM