How can I get the a certificate's validity period using Apple's Security framework?

1.3k views Asked by At

I am parsing certificates inside macOS app's code signature and I want to get the expiration date (aka "validity period"). According to Apple's documentation the certificate contains a validity period but there is no function mentioned for retrieving it.

I am currently manually digging into the certificate and grabbing the value manually using SecCertificateCopyValues() from the dictionary but this does not seem to be the proper approach.

How can I get a SecCertificateRef's validity period (NSDate) in CoreFoundation or Foundation (Objective-C) using Apple's Security framework (not OpenSSL)?

Thank you.

1

There are 1 answers

0
Anubis On

For those who are interested in my approach I'll leave my snippet here. Cheers!


#import <Foundation/Foundation.h>

id getX509ValueforKey(SecCertificateRef certificate, CFStringRef kSecPropertyKey) {
    id value;
    CFDictionaryRef valuesDict = SecCertificateCopyValues(certificate, (__bridge CFArrayRef)@[(__bridge id)kSecPropertyKey], NULL);
    if (valuesDict) {
        CFDictionaryRef invalidityDateDictionaryRef = CFDictionaryGetValue(valuesDict, kSecPropertyKey);
        if (invalidityDateDictionaryRef) {
            CFTypeRef invalidityRef = CFDictionaryGetValue(invalidityDateDictionaryRef, kSecPropertyKeyValue);
            if (invalidityRef)
                value = CFBridgingRelease(invalidityRef);
        }
        CFRelease(valuesDict);
    }
    return value;
}

int main(int argc, const char * argv[]) {
    
    SecCertificateRef certificateRef = NULL;
    NSDate *certExpiryDate = getX509ValueforKey(certificateRef, kSecOIDInvalidityDate);
    NSLog(@"certExpiryDate: %@", certExpiryDate);
    
    return noErr;
}