/// <summary> /// Gets a list of all certificates suitable for the given key usage. /// </summary> /// <returns>The matching certificates.</returns> /// <param name="keyUsage">The key usage.</param> /// <exception cref="System.ObjectDisposedException"> /// The keychain has been disposed. /// </exception> public IList <X509Certificate> GetCertificates(CssmKeyUse keyUsage) { if (disposed) { throw new ObjectDisposedException("SecKeychain"); } var parser = new X509CertificateParser(); var certs = new List <X509Certificate> (); IntPtr searchRef, itemRef, certRef; OSStatus status; status = SecIdentitySearchCreate(Handle, keyUsage, out searchRef); if (status != OSStatus.Ok) { return(certs); } while (SecIdentitySearchCopyNext(searchRef, out itemRef) == OSStatus.Ok) { if (SecIdentityCopyCertificate(itemRef, out certRef) == OSStatus.Ok) { using (var data = new CFData(SecCertificateCopyData(certRef), true)) { var rawData = data.GetBuffer(); try { certs.Add(parser.ReadCertificate(rawData)); } catch (CertificateException ex) { Debug.WriteLine("Failed to parse X509 certificate from keychain: {0}", ex); } } } CFRelease(itemRef); } CFRelease(searchRef); return(certs); }
static extern OSStatus SecIdentitySearchCreate(IntPtr keychainOrArray, CssmKeyUse keyUsage, out IntPtr searchRef);
/// <summary> /// Gets a list of all certificates suitable for the given key usage. /// </summary> /// <returns>The matching certificates.</returns> /// <param name="keyUsage">The key usage.</param> /// <exception cref="System.ObjectDisposedException"> /// The keychain has been disposed. /// </exception> public IList<X509Certificate> GetCertificates(CssmKeyUse keyUsage) { if (disposed) throw new ObjectDisposedException ("SecKeychain"); var parser = new X509CertificateParser (); var certs = new List<X509Certificate> (); IntPtr searchRef, itemRef, certRef; OSStatus status; status = SecIdentitySearchCreate (Handle, keyUsage, out searchRef); if (status != OSStatus.Ok) return certs; while (SecIdentitySearchCopyNext (searchRef, out itemRef) == OSStatus.Ok) { if (SecIdentityCopyCertificate (itemRef, out certRef) == OSStatus.Ok) { using (var data = new CFData (SecCertificateCopyData (certRef), true)) { var rawData = data.GetBuffer (); try { certs.Add (parser.ReadCertificate (rawData)); } catch (CertificateException ex) { Debug.WriteLine ("Failed to parse X509 certificate from keychain: {0}", ex); } } } CFRelease (itemRef); } CFRelease (searchRef); return certs; }