I have a project where I receive an encrypted RSA private key for a user from a server. Using information provided by the user, I am able to decrypt the data back into an expected format. However, I cannot figure out how to load the private key into the iOS Keychain for use in RSA crypto functions.
Currently, I have the following code that I have cobbled together from various examples. This code works will for adding a public key, but doesn't seem to work at all for adding a private key.
[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:privateKeyData forKey:(__bridge id)kSecValueData];
[peerPublicKeyAttr setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecReturnRef];
sanityCheck = SecItemDelete((__bridge CFDictionaryRef) peerPublicKeyAttr) ;
sanityCheck = SecItemAdd((__bridge CFDictionaryRef) peerPublicKeyAttr, (CFTypeRef *)&privateKey);
When I run this code with the private key data (decoded into DER format), the privateKey
variable is set to NULL by the SecItemAdd()
call. However, the sanityCheck
variable indicates "No Error". I'm at a loss for what I'm missing.
What do I need to do to get the private key to load into the keychain successfully?
Official response from Apple on this exact subject was that it was unsupported. The only supported way of getting private keys into the Keychain was through PKCS#12 files.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With