Saving SecKeyRef device generated public/private key pair on disk
Ah, found the answer myself; you can get the bytes for a public key using SecItemCopyMatching()
.
- (NSData *)getPublicKeyBits { OSStatus sanityCheck = noErr; NSData * publicKeyBits = nil; NSMutableDictionary * queryPublicKey = [[NSMutableDictionary alloc] init]; // Set the public key query dictionary. [queryPublicKey setObject:(id)kSecClassKey forKey:(id)kSecClass]; [queryPublicKey setObject:publicTag forKey:(id)kSecAttrApplicationTag]; [queryPublicKey setObject:(id)kSecAttrKeyTypeRSA forKey:(id)kSecAttrKeyType]; [queryPublicKey setObject:[NSNumber numberWithBool:YES] forKey:(id)kSecReturnData]; // Get the key bits. sanityCheck = SecItemCopyMatching((CFDictionaryRef)queryPublicKey, (CFTypeRef *)&publicKeyBits); if (sanityCheck != noErr) { publicKeyBits = nil; } [queryPublicKey release]; return publicKeyBits;}
The above is from Apple's CryptoExercise. Not sure if it works for private keys though.
You can use the latest crypto API of iOS, You can save the key as NSData and retrieve the key from NSData
SecKeyRef key = <# a key #>;CFErrorRef error = NULL;NSData* keyData = (NSData*)CFBridgingRelease( // ARC takes ownership SecKeyCopyExternalRepresentation(key, &error) );if (!keyData) { NSError *err = CFBridgingRelease(error); // ARC takes ownership // Handle the error. . .}
See the Encrypting and Decrypting Data section of the Certificate, Key, and Trust Services Programming Guide, which has code samples to generate, save, and use public/private key pairs.