我正在尝试将一个私钥添加到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
。这意味着没有为此键存储任何值。然后,当我尝试将私钥添加到Keychain时,我得到了-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:我发现它只在第一次起作用。即使数据和密钥不同,在将其存储到钥匙串中的第一次之后,我无法存储更多的密钥。