2013-06-04 6 views
6

Apple GenericKeychainサンプルのKeychainItemWrapperクラスは、パスワードを格納するためにkSecValueDataキーを使用します。iOSのキーチェーンにパスワードを保存するためにどのキーを使用する必要がありますか?

しかし参照http://developer.apple.com/library/ios/#documentation/Security/Reference/keychainservices/Reference/reference.html#//apple_ref/doc/uid/TP30000898

はkSecValueDataが返される値のタイプを示す、SecItemCopyMatching又はSecItemAddの結果辞書で使用 と言います。

キーチェーンアイテムを作成するためにSecItemAddを呼び出すときに使用するキーは何ですか?

答えて

7

(NSDataまたはCFDataRef形式の)パスワードを保存するキーとしてkSecValueデータを使用する必要があります。

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 
} 
+0

より良いコードを、ここでは少数のバグ、と:ここ

は、両方の例例のHTTP:/ /stackoverflow.com/questions/19284063/secitemcopymatching-returns-nil-data –

関連する問題