覆盖默认 HashAlgorithm.Create()

Override default HashAlgorithm.Create()

我一直在尝试将 SHA1 的默认值覆盖为 System.Security.Cryptography.HashAlgorithm.Create() returns 的 SHA256。基于 docs,它应该是可覆盖的。

我遇到了这个 article,但它似乎只提到映射自定义哈希算法以覆盖现有算法之一。我只想将 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.NET\Framework\[version]\config\machine.config

x64:

%windir%\Microsoft.NET\Framework64\[version]\config\machine.config 

您还可以通过更改 DefaultHashAlgorithm 属性更改每个内置哈希算法的默认算法。请参阅算法列表 here

更改 machine.config 的缺点是它会影响所有将使用 System.Security.Cryptography.HashAlgorithm 的应用程序。

另一种方法是使用CryptoConfig class。下一个代码片段将 SHA256Managed 注册为默认哈希算法:

using System.Security.Cryptography;

...

CryptoConfig.AddAlgorithm(
    typeof(SHA256Managed),
    "System.Security.Cryptography.HashAlgorithm");

这仅更改当前应用程序的默认哈希算法。

注意必须使用抽象classSHA256的具体实现SHA256Managed