"CryptographicException: Invalid provider type specified" 仅在 WebAPI 项目中

"CryptographicException: Invalid provider type specified" only in WebAPI project

我有以下代码使用安装在本地计算机上的证书访问 KeyVault 中的机密:

static readonly string certThumbprint = "1234...";
static readonly string clientId = "1234...";

static void Main(string[] args)
{
    X509Certificate2 certificate = FindCertificateByThumbprint(certThumbprint);
    ClientAssertionCertificate assertionCert = new ClientAssertionCertificate(clientId, certificate);

    var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(
            (authority, resource, scope) => GetAccessToken(authority, resource, scope, assertionCert)));


    string url = "https://myvault.vault.azure.net/";
    var result = keyVaultClient.GetSecretAsync(url, "mySecret").Result;
}

private static X509Certificate2 FindCertificateByThumbprint(string certificateThumbprint)
{
    if (certificateThumbprint == null)
    {
        throw new System.ArgumentNullException("CertificateThumbprint");
    }

    StoreLocation[] storeLocations = (StoreLocation[])Enum.GetValues(typeof(StoreLocation));

    foreach (StoreLocation location in storeLocations)
    {
        foreach (StoreName storeName in (StoreName[])
            Enum.GetValues(typeof(StoreName)))
        {
            X509Store store = new X509Store(storeName, location);

            store.Open(OpenFlags.ReadOnly);

            X509Certificate2Collection certCollection = store.Certificates.Find(X509FindType.FindByThumbprint, certificateThumbprint, false);

            if (certCollection != null && certCollection.Count != 0)
            {
                foreach (X509Certificate2 cert in certCollection)
                {
                    if (cert.HasPrivateKey)
                    {
                        store.Close();
                        return cert;
                    }
                }
            }
        }
    }
    throw new Exception($"Could not find the certificate with thumbprint {certificateThumbprint} in any certificate store.");
}

private static async Task<string> GetAccessToken(string authority, string resource, string scope, ClientAssertionCertificate assertionCert)
{
    Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext context = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authority, TokenCache.DefaultShared);
    AuthenticationResult result = await context.AcquireTokenAsync(resource, assertionCert).ConfigureAwait(false);

    return result.AccessToken;
}

这在我的 .Net Framework 4.7.2 控制台应用程序中运行良好,安装了以下软件包:

  <ItemGroup>
    <PackageReference Include="Microsoft.Azure.KeyVault">
      <Version>3.0.5</Version>
    </PackageReference>
    <PackageReference Include="Microsoft.IdentityModel.Clients.ActiveDirectory">
      <Version>5.2.8</Version>
    </PackageReference>
    <PackageReference Include="System.Security.Cryptography.X509Certificates">
      <Version>4.3.2</Version>
    </PackageReference>
  </ItemGroup>

但是,当我 运行 在我的 WebAPI 项目 (.Net Framework 4.7.2) 上使用完全相同的代码时,我收到以下错误:

"ClassName": "System.Security.Cryptography.CryptographicException",
"Message": "Invalid provider type specified.\r\n"

根据 Nuget,我安装的包是相同的版本:

<Reference Include="Microsoft.Azure.KeyVault, Version=3.0.5.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
  <HintPath>..\packages\Microsoft.Azure.KeyVault.3.0.5\lib\net461\Microsoft.Azure.KeyVault.dll</HintPath>
</Reference>
<Reference Include="Microsoft.IdentityModel.Clients.ActiveDirectory, Version=5.2.8.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
  <HintPath>..\packages\Microsoft.IdentityModel.Clients.ActiveDirectory.5.2.8\lib\net45\Microsoft.IdentityModel.Clients.ActiveDirectory.dll</HintPath>
</Reference>
<Reference Include="System.Security.Cryptography.X509Certificates, Version=4.1.1.2, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
  <HintPath>..\packages\System.Security.Cryptography.X509Certificates.4.3.2\lib\net461\System.Security.Cryptography.X509Certificates.dll</HintPath>
  <Private>True</Private>
  <Private>True</Private>
</Reference>
  

我猜是其他一些包导致了冲突并解决了所需库之一的错误版本,但我不确定如何诊断和解决。

出现此异常的最可能原因是证书的私钥存储在现代 CNG 密钥存储提供程序中,而不是旧版 CAPI 加密服务提供程序中。在此响应时,Azure Key Vault 已知与 CNG 存在兼容性问题,因此您应该尝试生成新证书和 select 旧 CAPI CSP 来存储密钥 material.