2014-05-01 89 views
0

如何成功從OS X中的鑰匙串中刪除項目?這是我迄今爲止,但它在SecItemDelete呼叫失敗。我是否需要在查詢字典中指定一些其他屬性?通過執行類似的操作,我可以成功地將鍵值對插入鑰匙串中。如何成功從OS X中的鑰匙串中刪除項目?

#define DELETE_SIZE 3 
bool delete_key_keychain(const char *cKeyValue, SecKeychainRef keychain) { 
    if (!keychain) 
     return false; 

    // Convert to CFString. 
    CFStringRef keyValue = CFStringCreateWithCString(NULL, cKeyValue, kCFStringEncodingUTF8); 
    if (!keyValue) 
     return false; 

    // Specify query parameters. 
    const void *keys[DELETE_SIZE] = { 
     kSecClass, 
     kSecUseKeychain, 
     kSecAttrAccount 
    }; 
    const void *values[DELETE_SIZE] = { 
     kSecClassGenericPassword, 
     keychain, 
     keyValue 
    }; 

    // Create query. 
    CFDictionaryRef query = CFDictionaryCreate(NULL, keys, values, GET_SIZE, NULL, NULL); 
    if (!query) { 
     CFRelease(keyValue); 
     return false; 
    } 

    // Run query. 
    OSStatus status = SecItemDelete(query); 
    CFRelease(query); 
    CFRelease(keyValue); 

    return status == errSecSuccess; 
} 

更新:根據這個link,我需要設置kSecAttrService屬性查詢。結果,我開始使用SecKeychainFindGenericPasswordSecKeychainItemDelete。這將成功刪除密碼,但隨後爲同一個帳戶添加不同的密碼可能導致崩潰。因此,我開始使用SecKeychainItemModifyAttributesAndData來修改密碼並且不要刪除密碼。我相信這種不穩定可能是由於API執行的緩存。

回答

0

在過去,我用這個函數刪除特定的公鑰/私鑰對從我的Mac OS鑰匙串

// remove keypair from keychain 
- (BOOL)deleteKeysFromKeychain { 
    OSStatus sanityCheck1 = noErr; 
    OSStatus sanityCheck2 = noErr; 

    NSMutableDictionary * queryPublicKey = [[NSMutableDictionary alloc] init]; 
    NSMutableDictionary * queryPrivateKey = [[NSMutableDictionary alloc] init]; 

    // Set the public key query dictionary. 
    [queryPublicKey setObject:(__bridge id)kSecClassKey forKey:(__bridge id)kSecClass]; 
    [queryPublicKey setObject:self.myPublicTag forKey:(__bridge id)kSecAttrApplicationTag]; 
    [queryPublicKey setObject:(__bridge id)kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType]; 

    // Set the private key query dictionary. 
    [queryPrivateKey setObject:(__bridge id)kSecClassKey forKey:(__bridge id)kSecClass]; 
    [queryPrivateKey setObject:self.myPrivateTag forKey:(__bridge id)kSecAttrApplicationTag]; 
    [queryPrivateKey setObject:(__bridge id)kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType]; 

    // Delete the private key. 
    sanityCheck1 = SecItemDelete((__bridge CFDictionaryRef)queryPrivateKey); 

    // Delete the public key. 
    sanityCheck2 = SecItemDelete((__bridge CFDictionaryRef)queryPublicKey); 

    @autoreleasepool { 
     queryPrivateKey = nil; 
     queryPublicKey = nil; 
    } 

    return (sanityCheck1 == sanityCheck2 && sanityCheck2 == noErr ? YES : NO);  
} 

項目在哪裏myPublicTag是一樣的東西「com.yourAppName.publickey」

哪裏myPrivateTag是一樣的東西'com.yourAppName.privatekey'

也許這可能是有用的

+0

感謝您的回覆。原來問題是我沒有在我的查詢中設置'kSecAttrService'屬性。 –

相關問題