Skip to content

Instantly share code, notes, and snippets.

@chedabob
Created January 1, 2016 23:02
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chedabob/49eed109a3dfcad4bd41 to your computer and use it in GitHub Desktop.
Save chedabob/49eed109a3dfcad4bd41 to your computer and use it in GitHub Desktop.
/**
* Given a secKeyRef, puts it into the keychain to extract its data for easier comparison
*/
+ (NSData *)transformPublicKeyToData:(SecKeyRef)key
{
NSString *const keychainTag = @"X509_KEY";
NSData *publicKeyData;
OSStatus putResult, delResult = noErr;
// Params for putting the key first
NSMutableDictionary *putKeyParams = [NSMutableDictionary new];
putKeyParams[(__bridge id) kSecClass] = (__bridge id) kSecClassKey;
putKeyParams[(__bridge id) kSecAttrApplicationTag] = keychainTag;
putKeyParams[(__bridge id) kSecValueRef] = (__bridge id) (key);
putKeyParams[(__bridge id) kSecReturnData] = (__bridge id) (kCFBooleanTrue); // Request the key's data to be returned too
// Params for deleting the data
NSMutableDictionary *delKeyParams = [[NSMutableDictionary alloc] init];
delKeyParams[(__bridge id) kSecClass] = (__bridge id) kSecClassKey;
delKeyParams[(__bridge id) kSecAttrApplicationTag] = keychainTag;
delKeyParams[(__bridge id) kSecReturnData] = (__bridge id) (kCFBooleanTrue);
// Put the key
putResult = SecItemAdd((__bridge CFDictionaryRef) putKeyParams, (void *)&publicKeyData);
// Delete the key
delResult = SecItemDelete((__bridge CFDictionaryRef)(delKeyParams));
if ((putResult != errSecSuccess) || (delResult != errSecSuccess))
{
publicKeyData = nil;
}
return publicKeyData;
}
@shahdhiren
Copy link

Is reverse form possible? I want to get SecKeyRef from NSData for private key. I tried similar approach and it work for public key but not for private key. Is it possible for private key as well?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment