5

我正在尝试使用 iOS 安全框架与我的服务器进行安全通信。我有一个证书文件,我可以从中获取公钥参考。这就是我正在做的。

 NSString *certPath    = [[NSBundle mainBundle] pathForResource:@"supportwarriors.com" ofType:@"cer"];
 SecCertificateRef myCertificate = nil;

 NSData *certificateData   = [[NSData alloc] initWithContentsOfFile:certPath]; 
 myCertificate     = SecCertificateCreateWithData(kCFAllocatorDefault, (CFDataRef)certificateData);

 //got certificate ref..Now get public key secKeyRef reference from certificate..
 SecPolicyRef myPolicy   = SecPolicyCreateBasicX509();
 SecTrustRef myTrust;
 OSStatus status     = SecTrustCreateWithCertificates(myCertificate,myPolicy,&myTrust);  

    SecTrustResultType trustResult;
    if (status == noErr) {
        status = SecTrustEvaluate(myTrust, &trustResult);  
    }
 publicKey      = SecTrustCopyPublicKey(myTrust);

上面的代码在 iPhone 上完美运行,我已经测试过了。我能够安全地与我的服务器通信。但是当我尝试在 iPad 上(以 2 倍模式)运行我的应用程序时,上面的代码崩溃了。调试后,我发现 secTrustCreateWithCertificate 正在崩溃,并且崩溃日志如下所示。我使用的证书对于 iPad 和 iPhone 都是相同的……上面的 secCertificateCreateWithData 函数返回证书引用并且不是 nil ……那就是不是崩溃的原因..我做错了什么。

*** -[NSCFType count]: unrecognized selector sent to instance 0x14af24
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '***      -[NSCFType count]: unrecognized selector sent to instance 0x14af24'
4

1 回答 1

4

SecTrustCreateWithCertificates声称您可以通过单个证书或数组的文档。您收到的例外情况表明-[NSCFType count]: unrecognized selector sent to instance. iOS 3.2 中发生的情况SecTrustCreateWithCertificates是将输入值视为 CFArray 而不先检查它是否为单数SecCertificateRef.

为了解决这个问题,您可以执行类似于以下代码的操作:

    SecCertificateRef certs[1] = { certificate };
    CFArrayRef array = CFArrayCreate(NULL, (const void **) certs, 1, NULL);
    if(SecTrustCreateWithCertificates(array, x509Policy, &trustChain) == errSecSuccess)

只要记住CFRelease(array)在适当的范围内。

于 2011-02-17T03:01:14.710 回答