简体   繁体   中英

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.

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);

This page has some great tips and sample code for packaging the data you have into the PEM format so you can send it to a server:

http://blog.wingsofhermes.org/?p=42

You don't need the whole openssl library compiled from source and statically linked to do it. I'm using just this technique, wrapping the base 64 key in "-----BEGIN PUBLIC KEY-----" and it can be read and used by a Rails application using the standard ruby openssl classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM