iOS - RSA公钥SecKeyRef到NSData

时间:2014-10-14 17:23:41

标签: ios cryptography keychain

我有一个密钥对存储在iOS钥匙串中。我能够为公钥和私钥获取SecKeyRef个对象,没有任何问题。但是,我需要将公钥的SecKeyRef转换为NSData对象。我在this answer ...

中尝试了以下代码
- (NSData *)getPublicKeyBitsFromKey:(SecKeyRef)givenKey {

    static const uint8_t publicKeyIdentifier[] = "com.your.company.publickey";
    NSData *publicTag = [[NSData alloc] initWithBytes:publicKeyIdentifier length:sizeof(publicKeyIdentifier)];

    OSStatus sanityCheck = noErr;
    NSData * publicKeyBits = nil;

    NSMutableDictionary * queryPublicKey = [[NSMutableDictionary alloc] init];
    [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];

    // Temporarily add key to the Keychain, return as data:
    NSMutableDictionary * attributes = [queryPublicKey mutableCopy];
    [attributes setObject:(__bridge id)givenKey forKey:(__bridge id)kSecValueRef];
    [attributes setObject:@YES forKey:(__bridge id)kSecReturnData];
    CFTypeRef result;
    sanityCheck = SecItemAdd((__bridge CFDictionaryRef) attributes, &result);
    if (sanityCheck == errSecSuccess) {
        publicKeyBits = CFBridgingRelease(result);

        // Remove from Keychain again:
        (void)SecItemDelete((__bridge CFDictionaryRef) queryPublicKey);
    }

    return publicKeyBits;
}

...但是,当我运行它时,我得到的OSStatus值为-50,这表示某处有一个错误的参数。但是,我无法找到可能存在的问题。我在代码中遗漏了什么吗?或者有更好的方法将SecKeyRef转换为NSData对象吗?非常感谢您提供的任何帮助。

0 个答案:

没有答案