2014-09-22 59 views
2

我試圖獲得CFDataRef持久性參考,用於我的SecIdentityRef身份。但是,使用Apple提供的標準代碼時,函數返回0x0 CFDataRef。輸入參數不是零,但它不能再工作了。代碼使用完美。使用CFDataRef將證書保存到鑰匙串

CFTypeRef persistent_ref; 

CFDataRef persistentRefForIdentity(SecIdentityRef identity) 
{ 
    const void *keys[] = { kSecReturnPersistentRef, kSecValueRef }; 
    const void *values[] = { kCFBooleanTrue, identity }; 

    CFDictionaryRef dict = CFDictionaryCreate(NULL, keys, values, 2, NULL, NULL); 

    OSStatus status = SecItemAdd(dict, &persistent_ref); // `SecItemAdd` returns 0 

    if (dict) 
     CFRelease(dict); 

    return (CFDataRef)persistent_ref; 
} 

status是0,但仍然persistent_ref沒有價值。

有誰知道發生了什麼問題?

+0

看的像清單2-3從https://developer.apple.com/library/ios/DOCUMENTATION/Security/Conceptual/CertKeyTrustProgGuide/iPhone_Tasks/iPhone_Tasks.html#//apple_ref/doc/uid/TP40001358 -CH208-SW13。你有沒有像清單2-1那樣獲得身份? – 2014-09-22 10:54:35

+0

'presistent_ref'中的問題可能是全局變量。可能會改變其他方法嗎?使其成爲本地。 – 2014-09-22 10:57:27

+0

是的,我正在從PKCS-12數據中獲取身份。當試圖使變量'persistent_ref'本地時,它仍然是0x0。 – Hidde 2014-09-22 20:54:31

回答

1

使CFTypeRef persistent_ref成爲局部變量。或者在調用SecItemAdd函數之前確保將它設置爲NULL。請參閱下面的代碼。

CFDataRef persistentRefForIdentity (SecIdentityRef identity) 
{ 
    OSStatus status = errSecSuccess; 

    CFTypeRef persistent_ref = NULL; 
    const void *keys[] = { kSecReturnPersistentRef, kSecValueRef }; 
    const void *values[] = { kCFBooleanTrue,   identity }; 

    CFDictionaryRef dict = CFDictionaryCreate(NULL, keys, values, 2, NULL, NULL); 

    // Delete anything already added 
    SecItemDelete(dict); 

    //Add the new one 
    status = SecItemAdd (dict, &persistent_ref); 

    if (status != errSecSuccess) 
    return nil; 

    if (dict) 
     CFRelease(dict); 

    return (CFDataRef)persistent_ref; 
}