gpt4 book ai didi

c# - 加密异常 : 'Invalid algorithm specified' when using SHA-512

转载 作者:太空宇宙 更新时间:2023-11-03 14:46:21 30 4
gpt4 key购买 nike

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

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

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

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)

最近发生在一位使用 Windows 7 SP1 的客户身上。

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

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

最佳答案

如果您正在使用 cert.GetRSAPrivateKey() 并且它返回一个 RSACryptoServiceProvider 实例表明它不是来自 PFX,而是来自具有老司机由于您说它来自 .p12/.pfx,因此 PFX 可能包含对 CNG 未接管的常用加密服务提供商名称的引用(但我从未在软件 key 中看到过)。 (奥卡姆 Razor 有一个疑问:你确定他们不是不小心用错了证书吗?)

如果您知道它来自 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;
}
}
}

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


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

关于c# - 加密异常 : 'Invalid algorithm specified' when using SHA-512,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54013337/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com