在iOS上解码多个DER证书

时间:2016-07-28 01:07:21

标签: ios xcode certificate

我有一个CFDataRef,其中包含一个DER编码的X.509证书,我可以使用它创建一个SecCertificateRef,如下所示:

CFDataRef binaryDataRef = ... // from third party
SecCertificateRef certRef = SecCertificateCreateWithData (NULL, binaryDataRef);

但在某些情况下,我的CFData可以包含使用i2d_X509通过第三方代码连接在一起的多个证书(证书链)。

在iOS上有类似于SecCertificateCreateWithData的调用可以解码所有证书吗? SecCertificateCreateWithData只是给了我第一个证书。

1 个答案:

答案 0 :(得分:0)

I figured it out - I can use d2i_X509 to figure out where each cert is, and it handily adjusts the pointer to the next one in the array.

CFArrayRef nmCopyEncodedCertificates(CFDataRef derDataRef) {
    CFMutableArrayRef certs = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);

    if (derDataRef) {        
        CFIndex bytesRemaining = CFDataGetLength(derDataRef);
        const unsigned char *pDerData = CFDataGetBytePtr(derDataRef);
        const unsigned char *pCurCertBegin = pDerData;
        X509 *certX509 = NULL;

        while ((certX509 = d2i_X509(NULL, &pDerData, bytesRemaining)) != NULL &&    // increments pDerData to next cert
               bytesRemaining > 0) {
            X509_free(certX509);
            long len = pDerData - pCurCertBegin;
            if (len > 0) {
                CFDataRef certData = CFDataCreate(kCFAllocatorDefault, pCurCertBegin, len);
                if (certData) {
                    SecCertificateRef certRef = SecCertificateCreateWithData (kCFAllocatorDefault, certData);
                    if (certRef) {
                        CFArrayAppendValue(certs, certRef);
                        CFRelease(certRef);
                    }
                    CFRelease(certData);
                }
                bytesRemaining -= len;
                pCurCertBegin = pDerData;
            } else {
                break;
            }
        }
    }
    return certs;
}