Search code examples
c#cryptographysha256hashalgorithm

Is there any difference between SHA256.Create() and HashAlgorithm.Create("SHA-256")?


Do these two code blocks return the same thing? Assume arr is the same byte[] in both examples:

Code sample 1

HashAlgorithm a = HashAlgorithm.Create("SHA-256");
var result = a.ComputeHash(arr);

Code sample 2

SHA256 b = SHA256.Create();
var result = b.ComputeHash(arr);

UPDATE: I got the sample project of creating AWS signature code in C# (which is written in .Net 4.5) and am trying to use its classes in a dotnetcode5 project and just because HashAlgorithm.Create() is not available in dotnetcode5 yet, I have decided to use the second approach instead of the first one. The problem is that the second example returns a canonical result witch is not valid in AWS.


Solution

  • SHA256.Create() does this internally:

    return (HashAlgorithm) CryptoConfig.CreateFromName("System.Security.Cryptography.SHA256");
    

    HashAlgorithm.Create("SHA-256") will result in this:

    return (SHA256) CryptoConfig.CreateFromName("SHA-256");
    

    Both of these calls will result in the creation of an instance of SHA256Managed.

    See https://msdn.microsoft.com/en-us/library/system.security.cryptography.cryptoconfig(v=vs.110).aspx#Anchor_5

    So there is no difference between these two approaches.