【问题标题】:Convert SecKeyRef to EC_KEY in iOS在 iOS 中将 SecKeyRef 转换为 EC_KEY
【发布时间】:2016-12-14 08:39:08
【问题描述】:

我正在从 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,我们如何转换私钥或者这是转换或使用私钥的任何方式? 寻找回应。 谢谢

【问题讨论】:

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


    【解决方案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);
    

    【讨论】:

    • “privateKeyLegnth”中必须给出什么?
    • 这个答案的第一部分(如何导出密钥)是正确的,但是导出的密钥与d2i_EC_PUBKEY不兼容。见:forums.developer.apple.com/message/84684#84684
    • 您不应该使用d2i_PrivateKey_bio 作为私钥吗?
    猜你喜欢
    • 2014-02-14
    • 1970-01-01
    • 2013-05-20
    • 2014-11-25
    • 2012-11-18
    • 2011-05-12
    • 2013-07-26
    相关资源
    最近更新 更多