iOS:在钥匙串中预安装 SSL 证书 - 以编程方式

问题描述:

我想在用户访问站点之前在钥匙串中安装/保存证书.我有一个 HTTPS 服务器,我的应用程序会在用户转到 https://mysite 之前对其进行身份验证.

I want to install/save a certificate in the keychain before the user visits the site. I have a HTTPS server, and my app authenticates the user before they go to https://mysite.

有没有办法通过钥匙串中的 POST 请求安装/保存证书,或者我可以将该证书(文件)复制到资源包以将其标记为受信任?

Is there a way that I can install/save the certificate via a POST request in the keychain or can I copy that certificate (the file) to the resource bundle to mark it trusted?

获得 der 格式的服务器证书后,您可以尝试以下代码:

Once you have the server certificate in der format you can try the following code:

+ (void) addCertToKeychain:(NSData*)certInDer
{
    OSStatus            err = noErr;
    SecCertificateRef   cert;

    cert = SecCertificateCreateWithData(NULL, (CFDataRef) certInDer);
    assert(cert != NULL);

    CFTypeRef result;

    NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          (id)kSecClassCertificate, kSecClass,
                          cert, kSecValueRef, 
                          nil];

    err = SecItemAdd((CFDictionaryRef)dict, &result);
    assert(err == noErr || err == errSecDuplicateItem);

    CFRelease(cert);
}

它会将证书添加到您的应用程序的钥匙串沙箱中,即没有其他应用程序会信任您的证书.

It will add the certificate to the keychain sandbox of your application i.e. no other application will trust your cert.