通过Security.frameworks
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
- (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
终端可以执行命令
1 |
security find-identity -v -p codesigning |
所以Cocoa代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
(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证书列表