What is the difference between Security.Cryptography.HMACSHA256.Create() and Security.Cryptography.KeyedHashAlgorithm.Create("HmacSHA256")?
-
Heh, good one. Could be part of a riddle book for C# or an obfuscated C# contest :)Maarten Bodewes– Maarten Bodewes2015-09-05 15:19:09 +00:00Commented Sep 5, 2015 at 15:19
2 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.
5 Comments
HMACSHA256 and HMACSHA1 both return SHA1 hashes?CryptoConfig.CreateFromName doesn't know anything about SHA256, it receives System.Security.Cryptography.HMAC as input and thus it creates default one for HMAC algorithm, which is SHA1.Create without specifying the declaring class. Isn't that also the case in the VisualStudio IDE and command line compilers for .NET? This sounds like a recipe for failure to me.HMACSHA256.Create to HMAC.Create.Nothing. Security.Cryptography.KeyedHashAlgorithm.Create("HmacSHA256") (reference source) uses reflection to lookup Security.Cryptography.HMACSHA256.
1 Comment
HMACSHA256 class did "override" the static Create method.