4

I'm fairly new to crypto on iOS, and I've been running into an error that I haven't been able to find a solution for:

Whenever I try to get a SecKeyRef to a public key in the iOS keychain and use it, I end up with a EXC_BAD_ACCESS error. The SecKeyRef (called "publicKeyReference" in my code below is initially set to NULL, but it should have a value after the SecItemCopyMatching method is called, which can be seen from the memory address in the debugger window.

Here's my code:

SecKeyRef publicKeyReference = NULL;
NSData* publicTag = [publicKeyIdentifier dataUsingEncoding:NSUTF8StringEncoding];


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

// Set the public key query dictionary.
[queryPublicKey setObject:(__bridge id)kSecClassKey forKey:(__bridge id)kSecClass];
[queryPublicKey setObject:publicTag forKey:(__bridge id)kSecAttrApplicationTag];
[queryPublicKey setObject:(__bridge id)kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
[queryPublicKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecReturnPersistentRef];

// Get the key.
sanityCheck = SecItemCopyMatching((__bridge CFDictionaryRef)queryPublicKey, (CFTypeRef *)&publicKeyReference);

// Encrypt using the public.
sanityCheck = SecKeyEncrypt(    publicKeyReference,
                       PADDING,
                       plainBuffer,
                       plainBufferSize,
                       &cipherBuffer[0],
                       &cipherBufferSize
                       );        

And Here's some screenshots of the error and the debug window:

Xcode Version of Code with error

Debugger Output

It seems that something is being assigned to the SecKeyRef, since the value of the address isn't "0x0", but I've been continually getting the EXC_BAD_ACCESS error regardless of what I've tried. Any and all help is greatly appreciated on the issue.

user1704620
  • 101
  • 2
  • 6
  • Have you looked at the first value of sanityCheck? It might reveal an error message from the SecItemCopy call. Also, note that you are using kSecReturnPersistentRef, which according to the comment in SecItem " indicates that a persistent reference to an item (CFDataRef) should be returned." So the response is potentially not of type SecKeyRef. – Henri Normak Apr 28 '15 at 12:51

1 Answers1

0

I got the same error with SecKeyCreateEncryptedData function (which is intended for replacing the usage of SecKeyEncrypt on iOS 10+ ), it is not caused by the SecKeyRef, but the CFDataRef which is the encrypted data. So I suggest to check the encrypted data like plainBuffer, plainBufferSize, etc.

Haven
  • 7,808
  • 5
  • 25
  • 37