如何通过代码从Mac Keychain中删除证书?

rad*_*adj 2 security macos certificate keychain

我查看了Apple的证书参考,我没有看到任何关于从Keychain中删除证书的信息.

是允许的吗?

如果是这样,怎么样?如果没有,为什么不呢?

Kar*_*tey 5

证书是钥匙串项的子类型,因此您可以使用SecKeychainItemDelete它们来删除它们.为了防止编译器警告,您需要显式地SecCertificateRef转换为SecKeychainItemRef- plain C没有对子类的语言支持.

SecCertificateRef certificate = ...;
OSStatus status = SecKeychainItemDelete((SecKeychainItemRef)certificate);
if (status) {
    // Handle error
}
Run Code Online (Sandbox Code Playgroud)

如果您的目标是Mac OS 10.6或更高版本,则还可以使用较新的SecItemDeleteAPI.在最简单的情况下,它不提供任何优势,但您可以更改查询参数以一次删除多个证书,或删除证书而不直接引用它们.

SecCertificateRef certificate = ...;
NSDictionary *query = [NSDictionary dictionaryWithObjectsAndKeys:
                       kSecClassCertificate, kSecClass,
                       [NSArray arrayWithObject:(id)certificate], kSecMatchItemList,
                       kSecMatchLimitOne, kSecMatchLimit,
                       nil];    
OSStatus status = SecItemDelete((CFDictionaryRef)query);
if (status) {
    // Handle error
}
Run Code Online (Sandbox Code Playgroud)