Security.Cryptography.HMACSHA256.Create()
和 Security.Cryptography.KeyedHashAlgorithm.Create("HmacSHA256")
有什么区别?
这两个方法都是用于创建HMAC-SHA256(使用SHA-256散列算法和密钥的哈希消息认证码)对象。主要区别在于第二种方法允许您选择哈希算法和密钥大小,而第一种方法使用默认值。因此,如果您需要更高级的控制,则可以使用第二种方法创建对象。
Security.Cryptography.HMACSHA256.Create()
和 Security.Cryptography.KeyedHashAlgorithm.Create("HmacSHA256")
有什么区别?
首先,关于 Security.Cryptography.HMACSHA256.Create()
--
Create
方法是 HMAC
类的方法,从中派生出 HMACSHA256
。简而言之:
public class HMACSHA256 : HMAC {
...
}
其中HMAC
的定义如下:
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);
}
...
}
其次,关于 Security.Cryptography.KeyedHashAlgorithm.Create("HmacSHA256")
public abstract class KeyedHashAlgorithm : HashAlgorithm {
new static public KeyedHashAlgorithm Create(String algName) {
return (KeyedHashAlgorithm) CryptoConfig.CreateFromName(algName);
}
...
}
CryptoConfig.CreateFromName
方法,但参数值不同,即在第一种情况下为System.Security.Cryptography.HMAC
,而在第二种情况下为HmacSHA256
。在CryptoConfig.CreateFromName
方法内部,有一些表和反射逻辑。SHA1
哈希值,而第二个调用的结果是SHA256
。HMACSHA256
和HMACSHA1
这两个类都返回SHA1
哈希值呢? - chaaruCryptoConfig.CreateFromName
对SHA256
一无所知,它接受System.Security.Cryptography.HMAC
作为输入,因此它会为HMAC
算法创建默认的SHA1
。 - Ulugbek UmirovHMACSHA256.Create
简化为HMAC.Create
。 - Ulugbek Umirov没有什么特别的。 Security.Cryptography.KeyedHashAlgorithm.Create("HmacSHA256")
(参考来源) 使用反射来查找 Security.Cryptography.HMACSHA256
。
HMACSHA256
类“覆盖”了静态的Create
方法,那么这可能是情况。 - Maarten Bodewes