首页 > 解决方案 > 使用 C# CertAddCRLContextToStore 导入 CRL

问题描述

我正在尝试使用 C# 中的 Win32 api CertAddCRLContextToStore 将 crl 添加到我的证书存储区。下面的代码在尝试将 crl 内容解析为 CRL_CONTEXT 时不起作用并且失败。我们可以通过其他方式做到这一点吗?或者我在我的代码中遗漏了什么?

    private const int CERT_STORE_PROV_SYSTEM = 10;
    private const int CERT_SYSTEM_STORE_LOCAL_MACHINE = (2 << 16);

    public const int CERT_QUERY_OBJECT_FILE = 0x00000001;
    public const int CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED = 1 << 8;
    public const int CERT_QUERY_FORMAT_FLAG_BINARY = 1 << 1;
    public const int CERT_STORE_ADD_REPLACE_EXISTING = 1 << 3;

    [DllImport("CRYPT32.DLL", CharSet = CharSet.Auto, SetLastError = true)]
    public static extern IntPtr CertOpenStore(
      int storeProvider,
      int encodingType,
      IntPtr hcryptProv,
      int flags,
      string pvPara);

    [DllImport("CRYPT32.DLL", EntryPoint = "CryptQueryObject", CharSet = CharSet.Auto, SetLastError = true)]
    public static extern bool CryptQueryObject(
        int dwObjectType,
        [MarshalAs(UnmanagedType.LPWStr)] String pvObject,
        int dwExpectedContentTypeFlags,
        int dwExpectedFormatTypeFlags,
        int dwFlags,
        IntPtr pdwMsgAndCertEncodingType,
        IntPtr pdwContentType,
        IntPtr pdwFormatType,
        IntPtr phCertStore,
        IntPtr phMsg,
        ref IntPtr ppvContext);

    [DllImport("crypt32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern bool CertAddCRLContextToStore(
      IntPtr hCertStore,
      IntPtr pCertContext,
      uint dwAddDisposition,
      IntPtr ppStoreContext);

    IntPtr hLocalCertStore = CertOpenStore(
              CERT_STORE_PROV_SYSTEM,
              0,
              IntPtr.Zero,
              CERT_SYSTEM_STORE_LOCAL_MACHINE,
              "CA");

    IntPtr pvContext = IntPtr.Zero;
    bool queryResult = CryptQueryObject(
            CERT_QUERY_OBJECT_FILE,
            @"sample.crl",
            CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED,
            CERT_QUERY_FORMAT_FLAG_BINARY,
            0,
            IntPtr.Zero,
            IntPtr.Zero,
            IntPtr.Zero,
            IntPtr.Zero,
            IntPtr.Zero,
            ref pvContext
        );

    // FAILS HERE 
    if (!queryResult)
    {
        throw new Exception("CryptQueryObject error #" + Marshal.GetLastWin32Error());
    }

    bool addResult = CertAddCRLContextToStore(
        hLocalCertStore, pvContext, CERT_STORE_ADD_REPLACE_EXISTING, IntPtr.Zero);

    if (!addResult)
    {
        throw new Exception("CryptQueryObject error #" + Marshal.GetLastWin32Error());
    }

代码因错误而失败

-2146885623。“找不到请求的对象”

标签: c#winapicryptographycertificate-revocation

解决方案


推荐阅读