我一直在尝试覆盖System.Security.Cryptography.HashAlgorithm.Create()
返回的SHA1
到SHA256
的默认值。基于文档,它应该是可重写的。
我看到了这篇文章,但它似乎只提到映射一个自定义哈希算法来覆盖现有的哈希算法。我只想将SHA1
的默认值覆盖为SHA256
的默认值。
使用上面的文章可能吗?
像这样的东西?
<configuration>
<mscorlib>
<cryptographySettings>
<cryptoNameMapping>
<nameEntry name="System.Security.Cryptography.HashAlgorithm"
class="System.Security.Cryptography.SHA256"/>
</cryptoNameMapping>
</cryptographySettings>
</mscorlib>
</configuration>
是,这是可能的。
如果您需要在机器上运行的每个.NET Framework应用程序中应用新的默认哈希算法,只需在machine.config
文件中写入以下部分:
<mscorlib>
<cryptographySettings>
<cryptoNameMapping>
<cryptoClasses>
<cryptoClass DefaultHashAlgorithm="System.Security.Cryptography.SHA256Managed, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
</cryptoClasses>
<nameEntry name="System.Security.Cryptography.HashAlgorithm"
class="DefaultHashAlgorithm"/>
</cryptoNameMapping>
</cryptographySettings>
</mscorlib>
注意machine.config
文件放在这里:
x32:
%windir%Microsoft.NETFramework[version]configmachine.config
x64:
%windir%Microsoft.NETFramework64[version]configmachine.config
此外,您还可以通过更改DefaultHashAlgorithm
属性来更改每个内置哈希算法的默认算法。请参阅此处的算法列表。
更改machine.config
的缺点是它会影响所有将使用System.Security.Cryptography.HashAlgorithm
的应用程序。
另一种方法是使用CryptoConfig
类。下一个代码片段将SHA256Managed
注册为默认哈希算法:
using System.Security.Cryptography;
...
CryptoConfig.AddAlgorithm(
typeof(SHA256Managed),
"System.Security.Cryptography.HashAlgorithm");
这只会更改当前应用程序的默认哈希算法。
注意必须使用抽象类SHA256
的具体实现SHA256Managed
。