OStack程序员社区-中国程序员成长平台

标题: iphone - SecTrustEvaluate() 是否在应用程序钥匙串(keychain)中查找根证书? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 16:33
标题: iphone - SecTrustEvaluate() 是否在应用程序钥匙串(keychain)中查找根证书?

文档说:“如果不是所有验证叶证书所需的证书都包含在信任管理对象中,那么 SecTrustEvaluate 在钥匙串(keychain)搜索列表(请参阅 SecTrustSetKeychains)和系统的 anchor 证书存储中搜索证书(请参阅 SecTrustSetAnchorCertificates)。”

但是,由于 SecTrustSetKeychains() 在 iOS 上不可用,尚不清楚此函数是否也会在应用程序的钥匙串(keychain)中查找。



Best Answer-推荐答案


好像你发帖已经有一段时间了,所以我不确定你是否还需要答案。如果您的用例是“我遇到了 connection:didReceiveAuthenticationChallenge:,并且我想确保正在评估 exact 证书,那么您可以使用 iOS 内置的信任方法或通过 Foundation API 做更多的工作注意这里没有专门调用 SecTrustEvaulate,但可以很容易地添加它)

#import <Security/Security.h>
#import <CommonCrypto/CommonDigest.h>

从那里,您可以迭代整个证书数组,并将其与挑战服务器信任引用的 SHA1 之类的东西进行比较:

// way #1 - iOS built-in ================================================ //
SecTrustRef trust = challenge.protectionSpace.serverTrust;
CFIndex cnt = SecTrustGetCertificateCount(trust);

// way #2 - build it in yourself from a file ============================ //
OSErr err;
NSString *path = [[NSBundle mainBundle] pathForResource"my.cert" 
                                                 ofType"der"];
NSData *derData = [NSData dataWithContentsOfFile:path];

SecCertificateRef myCert = 
    SecCertificateCreateWithData(NULL, (CFDataRef)derData);

CFMutableArrayRef array = CFArrayCreateMutable(NULL, 1, NULL);
CFArrayInsertValueAtIndex(array, 0, myCert);

err = SecTrustSetAnchorCertificates(trust, array);
if (err != errSecSuccess) {
    // do something smarter here, obviously, logging would be a start
    abort();
}
CFArrayRef certs = NULL;
err = SecTrustCopyCustomAnchorCertificates(trust, &certs);
if (err != errSecSuccess) {
    // again, better choices needed
    abort();
}
CFIndex cnt = CFArrayGetCount(certs);

// loop and compare 'em
for (int i = 0; i < cnt; i++) {
    SecCertificateRef cert = SecTrustGetCertificateAtIndex(trust, i);

    CFDataRef cdata = SecCertificateCopyData(cert);
    NSData *data = [[NSData alloc] initWithDataNSData *)cdata];

    unsigned char digest_result[CC_SHA1_DIGEST_LENGTH];

    CC_SHA1(data.bytes, data.length, digest_result);
    // compare each byte with your in-code SHA1 bytes
    if (allBytesMatch) {
        NSURLCredential *cred = [NSURLCredential credentialForTrust:trust];
        [challenge.sender useCredential:cred 
             forAuthenticationChallenge:challenge];
    }
}
// don't forget to release & CFRelease all the alloc'ed stuff from above

关于iphone - SecTrustEvaluate() 是否在应用程序钥匙串(keychain)中查找根证书?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4669255/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4