MVC 3在哪里加密用户的密码?

时间:2012-08-17 17:47:35

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

我有自己的密码加密dll,用于登录时检查用户的密码,这在我的用户实体中引用。

现在我已经创建了一个用户注册哪个工作正常的功能,除了密码还没有加密。

我的问题很简单,我应该在哪里加密新用户的密码?我不确定因为我知道用户的密码不应该以纯文本形式传输,因此我不知道调用加密函数的最佳位置在哪里:

  • 用户实体(加密dll已用于验证)。
  • 保存用户方法所在的用户存储库。
  • 控制用户创建视图的用户控制器。
  • 我还没考虑过的其他地方!

非常感谢

4 个答案:

答案 0 :(得分:6)

首先,对于客户端 - 服务器通信,我建议您使用SSL来识别不以纯文本格式传输的敏感信息(如密码)。

之后,通常的做法是不在任何地方保存密码(即使加密,但加密值也是如此。

您可以将哈希函数放入密码属性的set方法。这是一个例子:

public class Member
{
    private string _username;

    public string Username
    {
        get { return _username; }
        set { _username = value.ToLowerInvariant(); }
    }

    public string Passhash {get;set;}

    public void SetPassword(string password)
    {
        Passhash = Crypto.Hash(password);
    }

    public bool CheckPassword(string password)
    {
        return string.Equals(Passhash, Crypto.Hash(password));
    }
}

public static class Crypto
{
    public static string Hash(string value)
    {
        return Convert.ToBase64String(
            System.Security.Cryptography.SHA256.Create()
            .ComputeHash(Encoding.UTF8.GetBytes(value)));
    }
}

编辑:

正如Craig Stuntz所指出的,这个例子中的Hash代码非常简单。请参阅以下帖子,了解更安全的方式来隐藏密码:Hashing passwords with MD5 or sha-256 C#

答案 1 :(得分:5)

在服务层方法中,负责做两件事:

  1. 将您的加密层称为哈希密码(不加密)
  2. 调用您的用户存储库以使用散列密码
  3. 将用户实体持久保存到数据库

    控制器操作当然会与服务层通信。

答案 2 :(得分:3)

不要自己进行密码散列,甚至不考虑加密密码。

使这种安全的努力是巨大的。使用基于公开可用规范和算法的现有方法。

答案 3 :(得分:0)

//ENCODE

public string base64Encode(string sData)
{
try
{
byte[] encData_byte = new byte[sData.Length];

encData_byte = System.Text.Encoding.UTF8.GetBytes(sData);

string encodedData = Convert.ToBase64String(encData_byte);

return encodedData;

}
catch(Exception ex)
{
throw new Exception("Error in base64Encode" + ex.Message);
}
}

//DECODE

public string base64Decode(string sData)
    {
        try
        {
            System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();

            System.Text.Decoder utf8Decode = encoder.GetDecoder();

            byte[] todecode_byte = Convert.FromBase64String(sData);

            int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);

            char[] decoded_char = new char[charCount];

            utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);

            string result = new String(decoded_char);

            return result;
        }
        catch (Exception ex)
        {
            throw new Exception("Error in base64Decode" + ex.Message);
        }
    }

How to call 

string encode= base64Encode(val);

string decode= base64Decode(val);


This is very helpful to decode and encode your string(password)
相关问题