Override default HashAlgorithm.Create()

Viewed 339

I've been trying to override the default value from SHA1 to SHA256 of what System.Security.Cryptography.HashAlgorithm.Create() returns. Based off the docs, it is supposed to be override-able.

I came across this article, but it seems to only mention mapping a custom hash algorithm to override one of the existing ones. I want to just override the default of SHA1 to a default of SHA256.

Is that possible using the article above?

Something like this?

<configuration>  
   <mscorlib>  
      <cryptographySettings>  
         <cryptoNameMapping>    
            <nameEntry name="System.Security.Cryptography.HashAlgorithm"  
                       class="System.Security.Cryptography.SHA256"/>  
         </cryptoNameMapping>  
      </cryptographySettings>  
   </mscorlib>  
</configuration>
2 Answers

Yes, it's possible.

If you need to apply new default hash algorithm in every running .NET Framework application on machine just write this section inside machine.config file:

<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>  

Note that machine.config file placed here:

x32:

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

x64:

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

Also you can change default algorithm on every built-in hash algorithm by change DefaultHashAlgorithm attribute. See list of algorithms here.

The drawback of changing machine.config is that it affects all applications that will use System.Security.Cryptography.HashAlgorithm.

Another approach is to use CryptoConfig class. The next code snippet registers SHA256Managed as a default hash algorithm:

using System.Security.Cryptography;

...

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

This changes default hash algorithm only for current application.

Note that a concrete implementation SHA256Managed of an abstract class SHA256 must be used.

Related