用于在钥匙串中存储和检索p12证书的示例函数 - 目标C.

时间:2016-08-03 09:21:40

标签: objective-c keychain

我需要两个函数,一个用于存储iOS Keychain中的p12证书,另一个函数用于检索存储的p12证书。

yourObject.getResults().get(i).getFace().getThumbnail();

}

对于上面的函数,我发送的是从p12文件中获取的NSData。

1 个答案:

答案 0 :(得分:1)

您必须将其分为两个任务:

  1. 将证书从p12数据转换为SecIdentityRef。有了这个,我可以帮忙
  2. 将私钥和证书链存储在钥匙串中 - I'm struggling with this too,但与您相比,我已经迈出了几步。
  3. 要执行转换,这是我正在使用的代码:

    - (NSError *)setClientIdentityCertificateFromPKCS12Data: (NSData *)PKCS12Data withPassword: (NSString *)password
    {
        OSStatus securityError = errSecSuccess;
    
        const void *keys[] =   { kSecImportExportPassphrase };
        const void *values[] = { (__bridge CFStringRef)password };
        CFDictionaryRef optionsDictionary = NULL;
    
        optionsDictionary = CFDictionaryCreate(
                                               NULL, keys,
                                               values, (password.length!=0 ? 1 : 0),
                                               NULL, NULL);
        CFArrayRef items = NULL;
    
        securityError = SecPKCS12Import((__bridge CFDataRef)PKCS12Data,
                                        optionsDictionary,
                                        &items);
    
        if (securityError == 0) {
            CFDictionaryRef identityDic = (CFDictionaryRef)CFArrayGetValueAtIndex(items, 0);
    
            SecIdentityRef secIdentity = (SecIdentityRef)CFDictionaryGetValue(identityDic, kSecImportItemIdentity);
            CFArrayRef identityCertChain = (CFArrayRef)CFDictionaryGetValue(identityDic, kSecImportItemCertChain);
    
            securityError = [self setClientIdentity: secIdentity withCertificateChain: identityCertChain];
        }
    
        if (optionsDictionary) {
            CFRelease(optionsDictionary);
        }
    
        if (items) {
            CFRelease(items);
        }
    
        NSError *error = nil;
        if (securityError != errSecSuccess)
        {
            NSDictionary *info = nil;
    #if !TARGET_OS_IPHONE
            NSString *errorDescription = nil;
            errorDescription = (__bridge_transfer NSString *)SecCopyErrorMessageString(securityError, NULL);
            if (errorDescription)
            {
                info = @{ NSLocalizedDescriptionKey:errorDescription };
            }
    #endif
            error = [NSError errorWithDomain: NSOSStatusErrorDomain
                                        code: securityError
                                    userInfo: info];
        }
    
        return error;
    }