Hi,
New to the forum, I had some specific queries I wanted to discuss. My current goal is to encrypt NSData objects using Security Transforms, specified in the Apple Developer website. I managed to create a random symmetric key following the tutorial here, in the form of a SecKeyRef object.
The symmetric key performs flawlessly for both encryption and decryption. However, I need to store this key into the keychain, for which Im facing a lot of issues.
Firstly, using this method to store key into the keychain gives me an error -67712 : Invalid key object.
+(BOOL) addKeyToKeyChain:(SecKeyRef) key
{
NSString *tag = @"com.mykey";
NSData *tagData = [tag dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *addQuery = @{ (id)kSecClass: (id)kSecClassKey,
(id)kSecValueRef: (__bridge id)key,
(id)kSecAttrApplicationTag: tagData,
(id)kSecAttrKeyType: (id)kSecAttrKeyTypeAES,
};
OSStatus status = SecItemAdd((CFDictionaryRef)addQuery, NULL);
if(status != errSecSuccess) {
NSLog(@"%d", (int)status);
NSLog(@"Error in storing key to keychain");
return FALSE;
}
NSLog(@"Key successfully stored in keychain");
return TRUE;
}
If I create a key manually using this method
+ (NSString*)generateSecureKey
{
NSMutableData *data = [NSMutableData dataWithLength:256];
int result = SecRandomCopyBytes(kSecRandomDefault, 256, data.mutableBytes);
if (result != noErr) {
return nil;
}
return [data base64EncodedStringWithOptions:kNilOptions];
}
and try to store it by using kSecValueData instead of kSecValueRef, passing a CFString, generated and casted from the above method, the key item does appear in the keychain but it has missing values and im unable to delete it.
Using terminal command
security find-key -l com.mykey
does locate the key but lists invalid or missing data. I cant find any other way to delete this key other than drop the keychain altogether and reset it, which is a massive pain as I have to revoke and renable my xcode developer profile and certificates to get code signing to work.
Id like a solution to this :
1) How to delete a corrupt key from keychain, without resetting whole keychain. (Remember, im using the login keychain).
2) How to store a SecKeyRef key to the keychain and retrieve it without any loss.
Thanks in advance