如何使用种子方法加密密码?

时间:2015-08-21 14:01:15

标签: asp.net asp.net-mvc entity-framework encryption seeding

我想使用SimpleCrypto加密存储在Seed方法中的密码。

这是init类。

protected override void Seed(MainContext context)
    {
        Role role1 = new Role { RoleName = "Admin" };
        Role role2 = new Role { RoleName = "User" };


        User user1 = new User  { Email = "admin@gmail.com", UserId = 1, Firstname = "Admin", ImageSrc = "batman.gif", Surname = "test", Password = "123456", PasswordSalt="", IsActive = true, CreateDate = DateTime.UtcNow, Roles = new List<Role>() };
        User  user2 = new User  { Email = "user1@ymail.com", UserId = 2, Firstname = "User", ImageSrc = "batman.gif", Surname = "test", Password = "eee", PasswordSalt="", IsActive = true, CreateDate = DateTime.UtcNow, Roles = new List<Role>() };




        user1.Roles.Add(role1);
        user2.Roles.Add(role2);

        context.Users.Add(user1);
        context.Users.Add(user2);

        context.SaveChanges();
        }

我真的不知道如何将它们绑在一起。

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您可以这样做:

public class CustomPasswordHasher : IPasswordHasher
{

    public string HashPassword(string password, string salt)
    {
        //Using SHA1 (Any other method can be used here)
        SHA1 sha1 = System.Security.Cryptography.SHA1.Create();
        byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(salt + password + salt);
        byte[] hash = sha1.ComputeHash(inputBytes);
        return Convert.ToBase64String(hash);
    }

    public PasswordVerificationResult VerifyHashedPassword(string hashedPassword, string providedPassword)
    {
        providedPassword = HashPassword(providedPassword);
        return (providedPassword == hashedPassword ? PasswordVerificationResult.Success : PasswordVerificationResult.Failed);
    }
}

并在构造函数中调用它,如下所示:

 var ph = new CustomPasswordHasher();
 this.PasswordHash = ph.HashPassword(this.Password, this.PasswordSalt);