certfindcertificateinstore (crypt32)
Last changed: 65.54.188.148

.
Summary
Finds the first or next certificate context in a certificate store that matches a search criteria established by the dwFindType and its associated pvFindPara.

C# Signature:

[DllImport("crypt32.dll", SetLastError=true)]
static extern IntPtr CertFindCertificateInStore(IntPtr hCertStore,
   uint dwCertEncodingType, uint dwFindFlags, uint dwFindType,
   IntPtr pszFindPara, IntPtr pPrevCertCntxt);

VB .NET Signature:

Declare Function CertFindCertificateInStore Lib "crypt32.dll" ( _
   hCertStore As IntPtr, dwCertEncodingType As Integer, dwFindFlags As Integer, _
   dwFindType As Integer, pszFindPara As IntPtr, pPrevCertContext As IntPtr) As IntPtr

User-Defined Types:

None.

Notes:

None.

Tips & Tricks:

You can define overloads with pszFindPara defined as different types (such as string) to more easily handle different scenarios.

Sample Code:

  public class Simplecert
  {
    const string MY   = "MY";
    const string OTHERS   = "AddressBook";
    const uint PKCS_7_ASN_ENCODING    = 0x00010000;
    const uint X509_ASN_ENCODING       = 0x00000001;
    const uint CERT_FIND_SUBJECT_STR   = 0x00080007;

    static uint MY_ENCODING_TYPE    = PKCS_7_ASN_ENCODING | X509_ASN_ENCODING ;

    static string lpszCertSubject = "*" ;

    public static void Main()
    {
        IntPtr hSysStore  = IntPtr.Zero;
        IntPtr hCertCntxt = IntPtr.Zero;

        hSysStore = WinCapi.CertOpenSystemStore(IntPtr.Zero, MY) ;
        Console.WriteLine("Store Handle:\t0x{0:X}", hSysStore.ToInt32());

        if(hSysStore != IntPtr.Zero)
        {
            hCertCntxt=WinCapi.CertFindCertificateInStore(
                hSysStore,
                MY_ENCODING_TYPE,
                0,
                CERT_FIND_SUBJECT_STR,
                lpszCertSubject ,
                IntPtr.Zero) ;

            if(hCertCntxt != IntPtr.Zero)
            {  //use certcontext from managed code
                Console.WriteLine("CertContext:\t0x{0:X}", hCertCntxt.ToInt32()) ;
                X509Certificate foundcert = new X509Certificate(hCertCntxt);
                Console.WriteLine("\nFound certificate with SubjectName string \"{0}\"",lpszCertSubject);
                Console.WriteLine("SubjectName:\t{0}", foundcert.GetName());
                Console.WriteLine("Serial No:\t{0}", foundcert.GetSerialNumberString());
                Console.WriteLine("HashString:\t{0}" , foundcert.GetCertHashString());
            }
            else
                Console.WriteLine("Could not find SubjectName containing string \"{0}\"", lpszCertSubject);
        }
        //-------  Clean Up  -----------
        if(hCertCntxt != IntPtr.Zero)
            WinCapi.CertFreeCertificateContext(hCertCntxt);
        if(hSysStore != IntPtr.Zero)
            WinCapi.CertCloseStore(hSysStore, 0) ;
    }
  }

Alternative Managed API:

In the Web Services Development Kit (WSDK) Technology Preview and .NET Whidbey.

Documentation