在iOS中将SecKeyRef转换为EC_KEY

时间:2016-12-14 08:39:08

标签: ios objective-c c security key-pair

我正在从openSSL创建CSR但是由于OpenSSL没有将密钥存储在安全区域中,因此我选择目标C在安全区域中创建密钥对(私钥和公钥)并发送到OpenSSL以获取X509证书。我在NSData中成功获得公钥,然后转换const unsigned char * bitsOfKeyDataPublicKey = (unsigned char *) [publicKey bytes];,然后创建公钥EC_KEY*_ec_keyPublic = d2i_EC_PUBKEY(NULL,&bitsOfKeyDataPublicKey, publicKeyLegnth);。但是对于私钥,我们从目标c获得SecKeyRef,因此对于创建EC_Key我们如何转换私钥或者这是转换或使用私钥的任何方式? 寻找回应。 感谢

1 个答案:

答案 0 :(得分:1)

您可以将私钥从SecKeyRef更改为NSData

示例:

- (NSData *)getPrivateKeyBits {
    OSStatus sanityCheck = noErr;
    NSData * privateKeyBits = nil;

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

    // Set the public key query dictionary.

    [queryPrivateKey setObject:(id)kSecClassKey forKey:(id)kSecClass];
    [queryPrivateKey setObject:_privateTag forKey:(id)kSecAttrApplicationTag];
    [queryPrivateKey setObject:(id)kSecAttrKeyTypeEC forKey:(id)kSecAttrKeyType];
    [queryPrivateKey setObject:[NSNumber numberWithBool:YES] forKey:(id)kSecReturnData];

    // Get the key bits.
    sanityCheck = SecItemCopyMatching((__bridge CFDictionaryRef)queryPrivateKey, (void *)&privateKeyBits);

    if (sanityCheck != noErr) {
        privateKeyBits = nil;
    }
    else if (sanityCheck == errSecItemNotFound) {
        privateKeyBits = nil;
    }

    return privateKeyBits;
}

不要忘记使用用于生成私钥的_privateTag

现在您可以使用:

const unsigned char *bitsOfKeyDataPrivateKey = (unsigned char *) [[self getPrivateKeyBits] bytes];
EC_KEY *_ec_keyPrivate = d2i_EC_PUBKEY(NULL,&bitsOfKeyDataPrivateKey, privateKeyLegnth);