我想將私鑰添加到iOS鑰匙串中。證書(公鑰)工作正常,但私鑰拒絕...我完全困惑爲什麼下面的代碼不起作用。將私鑰添加到iOS鑰匙串
首先我檢查如果當前密鑰(=,所述鑰匙鏈的情況下,密鑰是鍵/值存儲)是鑰匙串「自由」。然後我要添加私鑰。
CFStringRef labelstring = CFStringCreateWithCString(NULL, [key cStringUsingEncoding:NSUTF8StringEncoding], kCFStringEncodingUTF8);
NSArray* keys = [NSArray arrayWithObjects:(__bridge id)kSecClass,kSecAttrLabel,kSecReturnData,kSecAttrAccessible,nil];
NSArray* values = [NSArray arrayWithObjects:(__bridge id)kSecClassKey,labelstring,kCFBooleanTrue,kSecAttrAccessibleWhenUnlocked,nil];
NSMutableDictionary* searchdict = [NSMutableDictionary dictionaryWithObjects:values forKeys:keys];
CFRelease(labelstring);
NSMutableDictionary *query = searchdict;
CFTypeRef item = NULL;
OSStatus error = SecItemCopyMatching((__bridge_retained CFDictionaryRef) query, &item);
if (error)
{
NSLog(@"Error: %ld (statuscode)", error);
}
if(error != errSecItemNotFound)
{
SecItemDelete((__bridge_retained CFDictionaryRef) query);
}
[query setObject:(id)data forKey:(__bridge id)kSecValueData];
OSStatus status = SecItemAdd((__bridge_retained CFDictionaryRef) query, &item);
if(status)
{
NSLog(@"Keychain error occured: %ld (statuscode)", status);
return NO;
}
調試輸出如下:
2012-07-26 15:33:03.772 App[15529:1b03] Error: -25300 (statuscode)
2012-07-26 15:33:11.195 App[15529:1b03] Keychain error occured: -25299 (statuscode)
第一錯誤代碼-25300
表示errSecItemNotFound
。所以這個鍵沒有存儲值。然後,當我嘗試將私鑰添加到鑰匙串時,我得到-25299
這意味着errSecDuplicateItem
。我不明白。這是爲什麼發生?
有沒有人有一個線索或暗示對此有何看法?
蘋果的錯誤代碼:提前
errSecSuccess = 0, /* No error. */
errSecUnimplemented = -4, /* Function or operation not implemented. */
errSecParam = -50, /* One or more parameters passed to a function where not valid. */
errSecAllocate = -108, /* Failed to allocate memory. */
errSecNotAvailable = -25291, /* No keychain is available. You may need to restart your computer. */
errSecDuplicateItem = -25299, /* The specified item already exists in the keychain. */
errSecItemNotFound = -25300, /* The specified item could not be found in the keychain. */
errSecInteractionNotAllowed = -25308, /* User interaction is not allowed. */
errSecDecode = -26275, /* Unable to decode the provided data. */
errSecAuthFailed = -25293, /* The user name or passphrase you entered is not correct. */
謝謝!
更新#1:我已經想通了,它僅適用於第一次。即使數據和密鑰不同,在第一次存儲到鑰匙串後,我無法存儲其他密鑰。
我面對完全一樣的問題。使用SecItemAdd添加第一個密鑰沒有問題,然後任何對SecItemAdd的連續調用都會失敗,並返回errSecDuplicateItem,儘管SecItemCopyMatching返回了errSecItemNotFound。你有沒有找到解決方案呢? – 100grams 2013-01-08 10:47:18