Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between .NET's HMAC and HMAC KeyedHashAlgorithm?

What is the difference between Security.Cryptography.HMACSHA256.Create() and Security.Cryptography.KeyedHashAlgorithm.Create("HmacSHA256")?

like image 235
chaaru Avatar asked Sep 16 '26 10:09

chaaru


1 Answers

First, about Security.Cryptography.HMACSHA256.Create() --

Create method is the method of HMAC class, from which HMACSHA256 is derived. In short:

public class HMACSHA256 : HMAC {
...
}

where HMAC is defined as:

public abstract class HMAC : KeyedHashAlgorithm {
    new static public HMAC Create () {
        return Create("System.Security.Cryptography.HMAC");
    }

    new static public HMAC Create (string algorithmName) {
        return (HMAC) CryptoConfig.CreateFromName(algorithmName);
    }
    ...
}

Second, about Security.Cryptography.KeyedHashAlgorithm.Create("HmacSHA256")

public abstract class KeyedHashAlgorithm : HashAlgorithm { 
    new static public KeyedHashAlgorithm Create(String algName) {
        return (KeyedHashAlgorithm) CryptoConfig.CreateFromName(algName);    
    }
    ...
}

As you can see, both calls result in calling CryptoConfig.CreateFromName method, but with different parameter values, i.e., System.Security.Cryptography.HMAC in first case, and HmacSHA256 in second case. Internally, there are some tables and reflection logic inside CryptoConfig.CreateFromName method.

The result of first call is SHA1 hash, and the result of second call is SHA256.

like image 91
Ulugbek Umirov Avatar answered Sep 19 '26 03:09

Ulugbek Umirov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!