2

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.

Dmytro Shevchenko
  • 33,431
  • 6
  • 51
  • 67
Ali Foroughi
  • 4,540
  • 7
  • 42
  • 66
  • 1
    So, it seems you should be asking *why* is there a difference between those two snippets and not *whether* there is a difference judging by your comment on the first answer. – Artjom B. Dec 02 '15 at 09:38
  • how are you comparing your byte arrays ? – Rohit Dec 02 '15 at 09:49

3 Answers3

4

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.

Dmytro Shevchenko
  • 33,431
  • 6
  • 51
  • 67
1

Both will result the same because the do call the same method internally

new static public SHA256 Create() {
    return Create("System.Security.Cryptography.SHA256");
}

new static public SHA256 Create(String hashName) {
    return (SHA256) CryptoConfig.CreateFromName(hashName);
}

static public HashAlgorithm Create(String hashName) {
    return (HashAlgorithm) CryptoConfig.CreateFromName(hashName);
}

the difference is just the return type (SHA256 is derived from HashAlgorithm)

Reference for SHA256, Reference for HashAlgorithm

Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
1

I think the main question that OP is missing is how to compare the two bytes array.

If you do something like:

    static void Main(string[] args)
    {           
        byte[] arr = Encoding.ASCII.GetBytes("sample");
        HashAlgorithm a = HashAlgorithm.Create("SHA-256");
        var resulthash = a.ComputeHash(arr);

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

        Console.WriteLine(StructuralComparisons.StructuralEqualityComparer.Equals(resulthash, resultsha ));
    }     

you will get correct response.

Note you can't do something like resulthash==resultsha that will return false.

Tallmaris
  • 7,605
  • 3
  • 28
  • 58
Rohit
  • 10,056
  • 7
  • 50
  • 82