I am trying to add an RSA public key to my iPhone keychain using the CryptoExercise SecKeyWrapper addPeerPublicKey:keyBits: . The logic of this method is that it first tries to add the key to the keychain, and if it is already there (sanityCheck==errSecDuplicateItem) , it tries to extract this key from the keychain by calling SecKeyItemCopyMatching() .
This is exactly what happens in my case: the key is already in the keychain, so calling SecKeyItemAdd() returns errSecDuplicateItem .
Then it tries to retrieve the existing key, but SecKeyItemCopyMatching() returns 0 (indicating that there was no error), but the second parameter ( peerKeyRef ) remains deselperately nil.
How is this possible? What is wrong with that?
Here is the [SecKeyWrapper addPeerPublicKey:keyBits:] code from the CryptoExercise example for reference:
- (SecKeyRef)addPeerPublicKey:(NSString *)peerName keyBits:(NSData *)publicKey { OSStatus sanityCheck = noErr; SecKeyRef peerKeyRef = NULL; CFTypeRef persistPeer = NULL; LOGGING_FACILITY( peerName != nil, @"Peer name parameter is nil." ); LOGGING_FACILITY( publicKey != nil, @"Public key parameter is nil." ); NSData *peerTag = [[NSData alloc] initWithBytes:(const void *) [peerName UTF8String] length:[peerName length]]; NSMutableDictionary *peerPublicKeyAttr = [[NSMutableDictionary alloc] init]; [peerPublicKeyAttr setObject:(__bridge id) kSecClassKey forKey:(__bridge id) kSecClass]; [peerPublicKeyAttr setObject:(__bridge id) kSecAttrKeyTypeRSA forKey:(__bridge id) kSecAttrKeyType]; [peerPublicKeyAttr setObject:peerTag forKey:(__bridge id) kSecAttrApplicationTag]; [peerPublicKeyAttr setObject:publicKey forKey:(__bridge id) kSecValueData]; [peerPublicKeyAttr setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id) kSecReturnPersistentRef]; sanityCheck = SecItemAdd((__bridge CFDictionaryRef) peerPublicKeyAttr, (CFTypeRef *) &persistPeer);
source share