【问题标题】:Certificate recreation after upgrading to .NET Framework 4.8升级到 .NET Framework 4.8 后重新创建证书
【发布时间】:2022-03-02 23:33:25
【问题描述】:

我已将我们的一个 Web 应用程序从 .NET Framework 4.6 升级到 4.8。在代码深处的某个地方,一个 XML 字符串被签名,这个签名的 XML 被发送回客户端,客户端将验证签名。 XML 签名使用SignedXml 类。

由于其遗留性质,SHA1 仍在使用(请耐心等待!)。为了在升级 .NET Framework 时不破坏这种行为,我必须在实际签署 XML 之前设置以下 AppContext 开关:

AppContext.SetSwitch("Switch.System.Security.Cryptography.Xml.UseInsecureHashAlgorithms", true);
AppContext.SetSwitch("Switch.System.Security.Cryptography.Pkcs.UseInsecureHashAlgorithms", true);

这解决了我本地机器上的所有问题,我可以成功签署 XML。

现在,在将新代码版本部署到我们的暂存环境中时,出现了一个新问题:XML 签名失败并出现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.Xml.SignedXml.ComputeSignature()

现在我偶然发现了this question,尤其是that particular answer
因此,我使用 certutil 检查了 CSP,得到了以下结果:

  • 本地 → Microsoft Enhanced RSA and AES Cryptographic Provider → 有效
  • 暂存 → Microsoft Enhanced Cryptographic Provider v1.0 → 不起作用

问题:是否有机会减轻这种行为,例如。 G。通过使用另一段代码对 XML 进行签名?还是我必须重新创建证书?

提前致谢!

【问题讨论】:

  • 您是否尝试针对不同版本的网络?您可能需要构建一个类库来使用目标 Net 4.6 进行加密,然后从 Net 4.8 应用程序调用该库。
  • @jdweng 这样就足够了吗?嵌入到 .NET 4.8 进程中的 .NET 4.6 程序集真的最终会在 4.6 中执行吗?
  • 源代码中有条件编译指令,用于库的目标选项工作。所以对于不同的目标,中间的 obj 文件是不同的。它仍然使用编译代码的机器上安装的 Net 版本运行。
  • @jdweng 我将签名代码移到了针对 .NET 4.6.2 的不同程序集中,但问题仍然存在。还有其他想法吗?
  • 原始代码是 4.6 还是 4.6.2?

标签: c# .net xml


【解决方案1】:

最后我找到了一个适合我的解决方案。主要有两点:

1。 将 CSP 添加到现有证书

SwissSign 为我们的暂存环境提供了证书(pemkey 文件),我们自己创建了 p12 文件。

通过在创建p12文件时指定OpenSSL参数CSP,可以设置正确的CSP。命令可能如下所示:
openssl pkcs12 -export -out Output.p12 -inkey My.key -in My.chain.pem -name My -CSP "Microsoft Enhanced RSA and AES Cryptographic Provider"

如果您只有p12 文件,您必须在调用之前将其从PKCS10 转换为PEM 格式:
openssl pkcs12 -in my.p12 -out my.pem

2。在应用启动时设置 AppContext 开关

如前所述,必须设置以下 AppContext 开关:

AppContext.SetSwitch("Switch.System.Security.Cryptography.Xml.UseInsecureHashAlgorithms", true);
AppContext.SetSwitch("Switch.System.Security.Cryptography.Pkcs.UseInsecureHashAlgorithms", true);

在我的例子中,我将开关设置在我实际签署 XML 的类的深处。因此,这段代码在处理第一个 Web 请求时在运行时执行。

在挖掘System.Security.Cryptography.Xml.SignedXml 的内部时,我发现一些 AppContext 开关实际上正在被缓存。我的更新太迟了。

现在我在应用程序启动时设置了开关,一切正常?

【讨论】:

    猜你喜欢
    • 2022-07-07
    • 2016-07-01
    • 2022-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-12
    • 1970-01-01
    相关资源
    最近更新 更多