Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone: How do you export a SecKeyRef or an NSData containing public key bits to the PEM format?

I've created a pair of keys using SecKeyGeneratePair. I'd now like to pass the public key to a server, but I'm not really sure how to proceed.

I have a function getPublicKeyBits (taken from Apple's CryptoExercise), but I don't really know what to do with the raw NSData. Here is the function:

- (NSData *)getPublicKeyBits {
    OSStatus sanityCheck = noErr;
    NSData* publicKeyBits = nil;
    NSData* publicTag = [[NSData alloc] initWithBytes:publicKeyIdentifier length:sizeof(publicKeyIdentifier)];
    CFDataRef cfresult = NULL;


    NSMutableDictionary * queryPublicKey = [[NSMutableDictionary alloc] init];

    // Set the public key query dictionary.
    [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];
    [queryPublicKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecReturnData];

    // Get the key bits.
    sanityCheck = SecItemCopyMatching((__bridge CFDictionaryRef)queryPublicKey, (CFTypeRef*)&cfresult); 


    if (sanityCheck != noErr)
    {
        publicKeyBits = nil;
    }
    else 
    {
        publicKeyBits = (__bridge_transfer NSData *)cfresult;
    }

    return publicKeyBits;
}

How do I take this raw byte data and turn it into something like PEM or some other format that a crypto library understands? Should I base64 encode it? Are there other things I need to do as well?

If it helps, I'm trying to use the public key with the M2Crypto library available for Python.

like image 672
Dr. Acula Avatar asked Apr 18 '12 04:04

Dr. Acula


1 Answers

I think you will want to look at http://www.openssl.org/docs/crypto/pem.html# maybe:

int PEM_write_PrivateKey(FILE *fp, EVP_PKEY *x, const EVP_CIPHER *enc,
                                    unsigned char *kstr, int klen,
                                    pem_password_cb *cb, void *u);
like image 198
Grady Player Avatar answered Sep 28 '22 18:09

Grady Player