0

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?

Community
  • 1
  • 1
hockeybro
  • 981
  • 1
  • 13
  • 41

2 Answers2

0

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.

Sunil Sharma
  • 2,653
  • 1
  • 25
  • 36
0

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

btnguyen
  • 51
  • 4