HMAC SHA1 对密钥和消息使用相同的值
我正在编写一些 C# 安全代码,当我看到它使用 HMACSHA1 类时,我正打算替换它。该代码用于对密码进行哈希处理以存储在数据库中。引起我注意的是它使用密码作为 HMAC 密钥,这正是计算哈希值的目的。那么,使用密钥和散列数据的数据可以吗?这会使安全性更强还是更弱?
伪代码:
string pwd = "My~!Cra2y~P@ssWord1#123$";
using (HMACSHA1 hasher = new HMACSHA1())
{
hasher.Key = encoding.GetBytes(pwd); // using password for the key
return BytesToHex(hasher.ComputeHash(encoding.GetBytes(pwd))); // computing the hash for the password
}
I'm working on some C# security code and was about to replace it when I saw that it was using the HMACSHA1 class. The code is used to hash a password for storing in the database. The thing that caught my eye was that it uses the password as the HMAC key which is exactly what is computing the hash for. So is using the data for both the key and the thing your hashing OK? Does this make the security stronger or weaker?
psuedo code:
string pwd = "My~!Cra2y~P@ssWord1#123$";
using (HMACSHA1 hasher = new HMACSHA1())
{
hasher.Key = encoding.GetBytes(pwd); // using password for the key
return BytesToHex(hasher.ComputeHash(encoding.GetBytes(pwd))); // computing the hash for the password
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它的强度与经过两次迭代的未加盐 SHA1 哈希值一样强。即相当弱。
由于缺少盐,攻击者可以创建彩虹表,或者简单地同时攻击数据库中的所有密码哈希值。
低迭代次数使得攻击速度更快,因为攻击者可以简单地尝试更多的候选密码。
您应该添加盐,并使用较慢的哈希方法,例如 PBKDF2 和 bcrypt。 .net 类 Rfc2898DeriveBytes 实现 PBKDF2,因此我建议使用那个。
It's about as strong as an unsalted SHA1 hash with two iterations. i.e. pretty weak.
The lack of salt allows an attack to create rainbow tables, or simply attack all password hashes in your database at the same time.
The low iteration count makes the attack fast, since the attacker can simply try more password candidates.
You should add a salt, and use a slower hashing method, such as PBKDF2 and bcrypt. The .net class Rfc2898DeriveBytes implements PBKDF2, so I recommend using that one.
我不推荐使用 HMACSHA1 来存储数据库密码,但是将 Key 设置为与密码相同确实会削弱 Key 在此用途中的用处。该密钥应该是秘密的,并用于确定底层哈希数据是否已更改。
对于密码,您应该使用 SALT+密码组合来提高 HASH 算法的安全性。我通常使用用户唯一的SALT,但与密码不同,例如用户号或初始注册IP地址。
另外,请记住,不再建议将 SHA1 作为哈希算法。
您可以参考MSDN以获得更清晰的信息理解。
I wouldn't recommend HMACSHA1 for database password storage, but setting the Key to be the same as the password does weaken the usefulness of the Key in this purpose. The key is supposed to be secret and used to determine if the underlying hashed data has changed.
For passwords you should be using a SALT+Password combination to increase the security of HASH algorithms. I usually use a SALT that is unique to the user, but not the same as the password, such as the user number or initial registration IP address.
Also, keep in mind that SHA1 is no longer recommended as a hashing algorithm.
You can reference MSDN for a clearer understanding.