MVC - 如何散列和盐 [英] MVC - How to hash and salt

查看:86
本文介绍了MVC - 如何散列和盐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设法让散列工作,但盐分仍然是一个问题..我一直在搜索和测试示例没有成功。这是我的哈希代码:

  [必需的] 
[StringLength(MAX,MinimumLength = 3,ErrorMessage =分钟3,最多50个字母)]
public string Password {get;组; }
public string Salt {get;组; }

哈希密码功能(无盐):

  public string HashPass(s​​tring password){

byte [] encodedPassword = new UTF8Encoding()。GetBytes(password);
byte [] hash =((HashAlgorithm)CryptoConfig.CreateFromName(MD5))。ComputeHash(encodedPassword);
string encoded = BitConverter.ToString(hash).Replace( - ,string.Empty).ToLower();

return encoded; //返回散列版本的密码
}



<注册:

  [HttpPost] 
public ActionResult Register(User user){
if(ModelState.IsValid){

var u = new User {
UserName = user.UserName,
Password = HashPass(user.Password)//调用散列法
};

db.Users.Add(u);
db.SaveChanges();

返回RedirectToAction(Login);
}
}返回View();

登入:

  public ActionResult Login(){
return View();

$ b [HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(User u){
if(ModelState.IsValid)
{
using(UserEntities db = new UserEntities()){

string readHash = HashPass(u.Password);

var v = db.Users.Where(a => a.UserName.Equals(u.UserName)&&
a.Password.Equals(readHash))。FirstOrDefault ();
if(v!= null){

return RedirectToAction(Index,Home); //登录后
}
}
}返回View(u);
}

到目前为止,

我更喜欢在我的代码中进行演示,因为我发现很难用单词理解。



我首先使用数据库。

解决方案

为了安全,不要试图重新发明轮子。使用基于身份验证的声明



如果您仍然必须管理用户名和密码,请使用基于哈希的邮件验证代码( HMAC



我还建议您花些时间阅读企业安全最佳实践。已经有聪明的人解决了这个问题,为什么要重新发明轮子。 .NET在那里有所有的好东西。



下面的例子:

  // ------ -------------- MyHmac.cs ------------------- 
public static class MyHmac
{
private const int SaltSize = 32;
$ b public static byte [] GenerateSalt()
{
using(var rng = new RNGCryptoServiceProvider())
{
var randomNumber = new byte [ SaltSize];

rng.GetBytes(randomNumber);

返回randomNumber;



$ b public static byte [] ComputeHMAC_SHA256(byte [] data,byte [] salt)
{
using( var hmac = new HMACSHA256(salt))
{
return hmac.ComputeHash(data);
}
}
}



// ----------------- --Program.cs ---------------------------
string orgMsg =原始消息;
string otherMsg =其他消息;


Console.WriteLine(.NET中的HMAC SHA256演示);

Console.WriteLine(----------------------);
Console.WriteLine();

var salt = MyHmac.GenerateSalt();

var hmac1 = MyHmac.ComputeHMAC_SHA256(Encoding.UTF8.GetBytes(orgMsg),salt);
var hmac2 = MyHmac.ComputeHMAC_SHA256(Encoding.UTF8.GetBytes(otherMsg),salt);


Console.WriteLine(Original Message Hash:{0},Convert.ToBase64String(hmac1));
Console.WriteLine(其他消息散列:{0},Convert.ToBase64String(hmac1));

注意:盐不必保密,可以与散列本身一起存储。这是为了增加来自彩虹表攻击的安全性。

I managed to get hash working, but the salt-part is still an issue.. I've been searching and testing examples without success. This is my code with hash:

        [Required]
        [StringLength(MAX, MinimumLength = 3, ErrorMessage = "min 3, max 50 letters")]
        public string Password { get; set; }
        public string Salt { get; set; }

Hash password function(without salt):

 public string HashPass(string password) { 

       byte[] encodedPassword = new UTF8Encoding().GetBytes(password);
       byte[] hash = ((HashAlgorithm) CryptoConfig.CreateFromName("MD5")).ComputeHash(encodedPassword);
       string encoded = BitConverter.ToString(hash).Replace("-", string.Empty).ToLower();

          return encoded;//returns hashed version of password
      }

Register:

        [HttpPost]
        public ActionResult Register(User user) {
            if (ModelState.IsValid) {

                        var u = new User {
                            UserName = user.UserName,                               
                            Password = HashPass(user.Password)//calling hash-method
                        };

                        db.Users.Add(u);
                        db.SaveChanges();

                    return RedirectToAction("Login");
                }
            }return View();    
        }

Login:

     public ActionResult Login() {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(User u) {
            if (ModelState.IsValid) 
            {
                using (UserEntities db = new UserEntities()) {

                    string readHash = HashPass(u.Password);

                    var v = db.Users.Where(a => a.UserName.Equals(u.UserName) &&
                                              a.Password.Equals(readHash)).FirstOrDefault();
                    if (v != null) {

                        return RedirectToAction("Index", "Home"); //after login
                    }
                }
            }return View(u);
        }

So far hash work.. But how do I make salt work here?

I would prefer a demonstrate on my code as I find it very hard to understand by words.

I'm using database first.

解决方案

When it comes to security don't try to reinvent the wheel. Use Claims based authentication.

If you still must manage usernames and passwords use Hash-based message authentication code (HMAC)

I would also recommend investing sometime and reading Enterprise Security Best Practices. There are already smarter people who solved this problems why reinvent the wheel. And .NET has all the goodies there.

Example below:

//--------------------MyHmac.cs-------------------
public static class MyHmac
{
    private const int SaltSize = 32;

    public static byte[] GenerateSalt()
    {
        using (var rng = new RNGCryptoServiceProvider())
        {
            var randomNumber = new byte[SaltSize];

            rng.GetBytes(randomNumber);

            return randomNumber;

        }
    }

    public static byte[] ComputeHMAC_SHA256(byte[] data, byte[] salt)
    {
        using (var hmac = new HMACSHA256(salt))
        {
            return hmac.ComputeHash(data);
        }
    }
}



//-------------------Program.cs---------------------------
string orgMsg = "Original Message";
        string otherMsg = "Other Message";


        Console.WriteLine("HMAC SHA256 Demo in .NET");

        Console.WriteLine("----------------------");
        Console.WriteLine();

        var salt = MyHmac.GenerateSalt();

        var hmac1 = MyHmac.ComputeHMAC_SHA256(Encoding.UTF8.GetBytes(orgMsg), salt);
        var hmac2 = MyHmac.ComputeHMAC_SHA256(Encoding.UTF8.GetBytes(otherMsg), salt);


        Console.WriteLine("Original Message Hash:{0}", Convert.ToBase64String(hmac1));
        Console.WriteLine("Other Message Hash:{0}", Convert.ToBase64String(hmac1));

NOTE: Salts do not have to be kept secret and can be stored alongside the hash itself. It's to increase security from rainbow table attack.

这篇关于MVC - 如何散列和盐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆