通过Security.frameworks
- (IBAction)loadCerList1:(id)sender {
NSDictionary *options = @{(__bridge id)kSecClass: (__bridge id)kSecClassCertificate,
(__bridge id)kSecMatchLimit: (__bridge id)kSecMatchLimitAll};
CFArrayRef certs = NULL;
__unused OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)options, (CFTypeRef *)&certs);
NSArray *certificates = CFBridgingRelease(certs);
[self.onePopUpButton removeAllItems];
for (int i=0;i<[certificates count];i++) {
SecCertificateRef certificate = (__bridge SecCertificateRef)([certificates objectAtIndex:i]);
NSString *name = CFBridgingRelease(SecCertificateCopySubjectSummary(certificate));
[self.onePopUpButton addItemWithTitle:name];
}
}
通过NSTask执行security find-identity
终端可以执行命令
security find-identity -v -p codesigning
所以Cocoa代码
(IBAction)loadCerList2:(id)sender {
[self.twoPopUpButton removeAllItems];
NSTask *certTask = [[NSTask alloc] init];
[certTask setLaunchPath:@"/usr/bin/security"];
[certTask setArguments:[NSArray arrayWithObjects:@"find-identity", @"-v", @"-p", @"codesigning", nil]];
NSPipe *pipe = [NSPipe pipe];
[certTask setStandardOutput:pipe];
[certTask setStandardError:pipe];
NSFileHandle *handle=[pipe fileHandleForReading];
[certTask launch];
[NSThread detachNewThreadSelector:@selector(watchGetCerts:) toTarget:self withObject:handle];
}
- (void)watchGetCerts:(NSFileHandle*)streamHandle {
@autoreleasepool {
NSString *securityResult = [[NSString alloc] initWithData:[streamHandle readDataToEndOfFile] encoding:NSASCIIStringEncoding];
// Verify the security result
if (securityResult == nil || securityResult.length < 1) {
// Nothing in the result, return
return;
}
NSArray *rawResult = [securityResult componentsSeparatedByString:@"\""];
NSMutableArray *tempGetCertsResult = [NSMutableArray arrayWithCapacity:20];
for (int i = 0; i <= [rawResult count] - 2; i+=2) {
NSLog(@"i:%d", i+1);
if (rawResult.count - 1 < i + 1) {
// Invalid array, don't add an object to that position
} else {
// Valid object
[tempGetCertsResult addObject:[rawResult objectAtIndex:i+1]];
[self.twoPopUpButton addItemWithTitle:[rawResult objectAtIndex:i+1]];
}
}
}
}
转载请注明:天狐博客 » Cocoa开发之获取Keychain证书列表