CryptographicException:使用 SHA-512 时“指定的算法无效”

Ros*_*oss 5 .net c# windows x509certificate2 sha512

在我的 WPF 应用程序 (.NET 4.6) 中,我需要使用 P12 证书文件来使用 SHA-512 算法对字符串进行签名(以包含在 Web 请求的标头中)。我这样做如下:

using (var rsa = myX509Certificate2.GetRSAPrivateKey()) {
  myBytes = rsa.SignData(
    Encoding.UTF8.GetBytes(stringToSign), 
    HashAlgorithmName.SHA512, 
    RSASignaturePadding.Pkcs1
  );
}
Run Code Online (Sandbox Code Playgroud)

这在测试中适用于几乎所有客户,但奇怪的客户会遇到以下异常:

System.Security.Cryptography.CryptographicException: Invalid algorithm specified.
  at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
  at System.Security.Cryptography.Utils.SignValue(SafeKeyHandle hKey, Int32 keyNumber, Int32 calgKey, Int32 calgHash, Byte[] hash, Int32 cbHash, ObjectHandleOnStack retSignature)
  at System.Security.Cryptography.Utils.SignValue(SafeKeyHandle hKey, Int32 keyNumber, Int32 calgKey, Int32 calgHash, Byte[] hash)
  at System.Security.Cryptography.RSACryptoServiceProvider.SignHash(Byte[] rgbHash, Int32 calgHash)
  at System.Security.Cryptography.RSACryptoServiceProvider.SignHash(Byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
  at System.Security.Cryptography.RSA.SignData(Byte[] data, Int32 offset, Int32 count, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
  at System.Security.Cryptography.RSA.SignData(Byte[] data, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
Run Code Online (Sandbox Code Playgroud)

最近,一位使用 Windows 7 SP1 的客户就遇到了这种情况。

我正在努力通过现有的问题或一般的谷歌找到答案。据我所知,这可能是由于在后台使用了不受支持的 Windows 加密服务提供程序,但我不确定,因为我自己无法复制该错误。

有什么想法可以通过代码或让受影响的客户安装任何特定的 Windows 更新来解决这个问题吗?

bar*_*njs 1

如果您正在使用cert.GetRSAPrivateKey()并且它返回一个RSACryptoServiceProvider实例,表明它不是来自 PFX,而是来自带有旧驱动程序的智能卡。既然你说它来自 .p12/.pfx,那么 PFX 可能包含对 CNG 没有接管的常用加密服务提供商名称的引用(但我从未在软件密钥中看到过该名称)。(奥卡姆剃刀提出了一个问题:你确定他们没有意外地使用了错误的证书吗?)

如果您知道它来自 PFX,并且已使用可导出位导入它,则可以手动将其从 RSACryptoServiceProvider 转换为 RSACng:

using (RSA rsa = cert.GetRSAPrivateKey())
{
    byte[] toSign = Encoding.UTF8.GetBytes(stringToSign);
    myBytes = null;

    try
    {
        myBytes = rsa.SignData(
            toSign, 
            HashAlgorithmName.SHA512, 
            RSASignaturePadding.Pkcs1);
    }
    catch (CryptographicException)
    {
        try
        {
            using (RSA rsaCng = new RSACng())
            {
                rsaCng.ImportParameters(rsa.ExportParameters(true));

                myBytes = rsaCng.SignData(
                    toSign,
                    HashAlgorithmName.SHA512, 
                    RSASignaturePadding.Pkcs1);
            }
        }
        catch
        {
        }

        if (myBytes == null)
        {
            // Let the original exception continue
            throw;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

(作为原始异常抛出的替代方案,您可以决定让“重试”异常被抛出)


或者,Windows 10 修复了许多 RSACryptoServiceProvider“无效算法”行为,因此他们可以随时尝试升级。