0
votes

I generated a private PKCS#12 key and then put it in PEM format, and sent it over to the iPhone app. I want to save this private key in the iPhone Keychain.

First, I removed the headers like "BEGIN RSA PRIVATE KEY". Then I converted the rest of it into NSData. Then, using code like this:

CFDictionaryRef issues in Swift

I was able to get a SecKeyRef from this private key.

Now I want to know how I can insert this SecKeyRef into the keychain using SecItemAdd?

2
have u tried to use any library ? - Sunil Sharma
No, what library would you suggest? - hockeybro
These libraries aren't that helpful, since I am trying to put a private Key, which is a PKCS12 converted NSData. I already converted it to SecKeyRef, just haven't figured out how to add a SecKeyRef, thats it. - hockeybro
try to convert SecKeyRef to nsdata again and store in keychain - Sunil Sharma

2 Answers

0
votes

Try to use this method to convert SecKeyRef to NSData

- (NSData *)getPublicKeyBitsFromKey:(SecKeyRef)givenKey {

    static const uint8_t publicKeyIdentifier[] = "com.your.company.publickey";
    NSData *publicTag = [[NSData alloc] initWithBytes:publicKeyIdentifier length:sizeof(publicKeyIdentifier)];

    OSStatus sanityCheck = noErr;
    NSData * publicKeyBits = nil;

    NSMutableDictionary * queryPublicKey = [[NSMutableDictionary alloc] init];
    [queryPublicKey setObject:(__bridge id)kSecClassKey forKey:(__bridge id)kSecClass];
    [queryPublicKey setObject:publicTag forKey:(__bridge id)kSecAttrApplicationTag];
    [queryPublicKey setObject:(__bridge id)kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];

    // Temporarily add key to the Keychain, return as data:
    NSMutableDictionary * attributes = [queryPublicKey mutableCopy];
    [attributes setObject:(__bridge id)givenKey forKey:(__bridge id)kSecValueRef];
    [attributes setObject:@YES forKey:(__bridge id)kSecReturnData];
    CFTypeRef result;
    sanityCheck = SecItemAdd((__bridge CFDictionaryRef) attributes, &result);
    if (sanityCheck == errSecSuccess) {
        publicKeyBits = CFBridgingRelease(result);

        // Remove from Keychain again:
        (void)SecItemDelete((__bridge CFDictionaryRef) queryPublicKey);
    }

    return publicKeyBits;
}

And then add it to keychain.
I hope this will solve your problem.

0
votes

This works for me:

  1. Convert the private key to PKCS#8 format.
  2. Strip header
  3. Add to keychain

These two libs could help: Swift: https://github.com/btnguyen2k/swift-rsautils Obj-C: https://github.com/ideawu/Objective-C-RSA