views:

1356

answers:

2

I have a couple of NSString objects that represent an RSA public-private keypair (not generated by SecKeyCreatePair, but by an external crypto library). How can I create SecKeyRef objects (which are required for the SecKeyDecrypt/Encrypt methods) from these NSString objects?

Do I need to import them into the Keychain first? If so, how?

Thanks!

+1  A: 

I dug this code up (BSD license) from the MYcrypto library. It seems to do what you want.

    SecKeyRef importKey(NSData *data, 
                    SecExternalItemType type,
                    SecKeychainRef keychain,
                    SecKeyImportExportParameters *params) {
    SecExternalFormat inputFormat = (type==kSecItemTypeSessionKey) ?kSecFormatRawKey :kSecFormatUnknown;
    CFArrayRef items = NULL;

    params->version = SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION;
    params->flags |= kSecKeyImportOnlyOne;
    params->keyAttributes |= CSSM_KEYATTR_EXTRACTABLE;
    if (keychain) {
        params->keyAttributes |= CSSM_KEYATTR_PERMANENT;
        if (type==kSecItemTypeSessionKey)
            params->keyUsage = CSSM_KEYUSE_ENCRYPT | CSSM_KEYUSE_DECRYPT;
        else if (type==kSecItemTypePublicKey)
            params->keyUsage = CSSM_KEYUSE_ENCRYPT | CSSM_KEYUSE_VERIFY | CSSM_KEYUSE_WRAP;
        else if (type==kSecItemTypePrivateKey)
            params->keyUsage = CSSM_KEYUSE_DECRYPT | CSSM_KEYUSE_SIGN;
    }
    if (!check(SecKeychainItemImport((CFDataRef)data, NULL, &inputFormat, &type,
                                     0, params, keychain, &items),
               @"SecKeychainItemImport"))
        return nil;
    if (!items || CFArrayGetCount(items) != 1)
        return nil;
    SecKeyRef key = (SecKeyRef)CFRetain(CFArrayGetValueAtIndex(items,0));
    CFRelease(items);
    return key; // caller must CFRelease
}
Patrick McCafferty
The code doesn't really work on the iPhone SDK, though it is fine for general Mac OS X development on an actual computer. Thanks anyway!
Anant
Toss in some `#if TARGET_IPHONE_SIMULATOR` and `#else` compiler directives and you can get something that works in the simulator and the device. (You've got the Mac version above, just hunt down the iPhone analogs. I'm in the midst of a similar task or I'd just answer myself.)
bbrown
@bbrown: not helpful at all dude
St3fan
A: 

I'm not sure if the code in this Apple developer forum thread works, but it seems like a direct answer to your question.

bbrown