开发者社区> 问答> 正文

能把SecKeyRef转换成NSData或者字符串么

现在需要从p12文件中解析公钥和私钥. 解析成为SecKeyRef类型的结构体,能转换成NSData或者字符串格式么

展开
收起
a123456678 2016-07-27 16:20:45 4079 0
1 条回答
写回答
取消 提交回答
  • - (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;
    }
    2019-07-17 20:00:48
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载