重写默认的HashAlgorithm.Create()



我一直在尝试覆盖System.Security.Cryptography.HashAlgorithm.Create()返回的SHA1SHA256的默认值。基于文档,它应该是可重写的。

我看到了这篇文章,但它似乎只提到映射一个自定义哈希算法来覆盖现有的哈希算法。我只想将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

最新更新