Skip to content

Instantly share code, notes, and snippets.

@iangray001
Last active May 28, 2024 09:12
Show Gist options
  • Save iangray001/d1a7ad9cfda411131171c427563fd38e to your computer and use it in GitHub Desktop.
Save iangray001/d1a7ad9cfda411131171c427563fd38e to your computer and use it in GitHub Desktop.
How to fetch certificates from the user's keychain using Swift
import Foundation
import Security
var dataTypeRef: CFTypeRef?
let rv = SecItemCopyMatching(
[
kSecClass: kSecClassCertificate,
kSecReturnAttributes: true,
kSecReturnRef: true,
kSecReturnData: true,
kSecMatchLimit: kSecMatchLimitAll
] as CFDictionary,
&dataTypeRef
)
var data : NSArray?
data = dataTypeRef as? NSArray
for element in data! {
let dict : NSDictionary = element as! NSDictionary
let cert : SecCertificate = dict.object(forKey: kSecValueRef) as! SecCertificate
let summary = SecCertificateCopySubjectSummary(cert);
print(summary ?? "")
}
@CodingMarkus
Copy link

You may want to update that code. First part with Swift 5 would be:

import Foundation
import Security

var dataTypeRef: CFTypeRef?
let rv = SecItemCopyMatching(
    [
        kSecClass: kSecClassCertificate,
        kSecReturnAttributes: true,
        kSecReturnRef: true,
        kSecReturnData: true,
        kSecMatchLimit: kSecMatchLimitAll
    ] as CFDictionary,
    &dataTypeRef
)

@iangray001
Copy link
Author

Yes I put this together back in the days of Swift 1 and 2, it is amazing how much the language has advanced. I've updated it in case someone finds it again, thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment