新的 ASP.net Identity 项目为网站安全带来了一些有用的代码和接口(interface)。要使用接口(interface)(而不是使用 MVC 5 模板中包含的标准 Entity Framework 实现)实现自定义系统,需要 IPasswordHasher
。
IPasswordHasher
接口(interface)
namespace Microsoft.AspNet.Identity
{
public interface IPasswordHasher
{
string HashPassword(string password);
PasswordVerificationResult VerifyHashedPassword(string hashedPassword, string providedPassword);
}
}
是否可以在 ASP.net Identity 中并通过此接口(interface)使用密码加盐来实现更安全的加密?
最佳答案
健康警告以下答案:了解您正在使用哪个版本的 ASP.Net Identity。如果源代码是 github 存储库中的较新版本之一,您应该直接引用源代码。
在我撰写本文时,密码处理程序的当前版本 ( 3.0.0-rc1/.../PasswordHasher.cs ) 与以下答案有显着不同。这个较新的版本支持多个哈希算法版本,并记录为(并且在您阅读本文时可能会进一步更改):
Version 2:
- PBKDF2 with HMAC-SHA1, 128-bit salt, 256-bit subkey, 1000 iterations.
- (See also: SDL crypto guidelines v5.1, Part III)
- Format:
{ 0x00, salt, subkey }
Version 3:
- PBKDF2 with HMAC-SHA256, 128-bit salt, 256-bit subkey, 10000 iterations.
- Format:
{ 0x01, prf (UInt32), iter count (UInt32), salt length (UInt32), salt, subkey }
- (All UInt32s are stored big-endian.)
原始答案对于 ASP.Net Identity 的原始版本仍然有效,如下:
<小时/>@jd4u 是正确的,但为了提供更多信息,这不适合他的答案的评论:
-
Microsoft.AspNet.Identity.PasswordHasher : IPasswordHasher
已经给你加盐了,- 更重要的是它使用
Rfc2898DeriveBytes
生成盐和哈希值, - 它使用行业标准 PBKDF2( SE discussion here 、 OWASP recommendation for PBKDF2 here )。
- 更重要的是它使用
- 默认
Microsoft.AspNet.Identity.UserManager<TUser>
实现使用Microsoft.AspNet.Identity.PasswordHasher
作为混凝土IPasswordHasher
-
PasswordHasher
反过来是(最终)System.Security.Cryptography.Rfc2898DeriveBytes
的一个非常简单的包装器。
所以,如果您要使用 Rfc2898DeriveBytes
,只需使用 PasswordHasher
- 所有繁重的工作都已经为您完成(希望是正确的)。
详细信息
PasswordHasher(当前)最终使用的完整代码的作用非常接近:
int saltSize = 16;
int bytesRequired = 32;
byte[] array = new byte[1 + saltSize + bytesRequired];
int iterations = SOME; // 1000, afaik, which is the min recommended for Rfc2898DeriveBytes
using (var pbkdf2 = new Rfc2898DeriveBytes(password, saltSize, iterations))
{
byte[] salt = pbkdf2.Salt;
Buffer.BlockCopy(salt, 0, array, 1, saltSize);
byte[] bytes = pbkdf2.GetBytes(bytesRequired);
Buffer.BlockCopy(bytes, 0, array, saltSize+1, bytesRequired);
}
return Convert.ToBase64String(array);
关于Asp.net 身份密码哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19957176/