Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: Adding a Private Key to the devices KeyChain

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?

like image 501
John Haager Avatar asked Nov 04 '22 02:11

John Haager


1 Answers

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.

like image 193
John Haager Avatar answered Nov 14 '22 22:11

John Haager