2012-08-17 54 views
2

我有我自己的密碼加密DLL,我用它來檢查用戶的密碼時,他們登錄,這是在我的用戶實體引用。MVC 3在哪裏加密用戶的密碼?

現在我已經創建了用戶註冊哪些工作正常的能力,除了密碼還有待加密。

我的問題很簡單,我應該在哪裏加密新用戶的密碼?我不知道用戶的密碼不應該以純文本傳輸,因此我不知道哪裏可以稱爲加密功能的最佳位置:

  • 用戶實體(其中加密dll已經用於驗證)。
  • 保存用戶方法所在的用戶存儲庫。
  • 控制用戶創建視圖的用戶控制器。
  • 我還沒有考慮過的其他地方!

非常感謝

回答

6

首先,對於客戶端 - 服務器通信,我建議您使用SSL來傳遞敏感信息(如密碼)不要以純文本格式傳輸。

之後,這是常見的做法,是不會在任何地方(甚至是加密保存密碼,但其中的哈希值

你可以把散列函數密碼屬性的設置方法下面是一個例子。:

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))); 
    } 
} 

編輯:

克雷格斯頓茨指出,在這個例子中,哈希代碼很簡單,請參見下面的職位更安全的方式來散列密碼:Hashing passwords with MD5 or sha-256 C#

+0

+1。存儲散列,而不是加密的密碼。 – CodingWithSpike 2012-08-17 18:00:20

+0

非常感謝,我喜歡這個答案,但是我使用實體框架,只要我將Password屬性更改爲Password類而不是字符串,它就不會從數據庫中獲取數據,這很有意義。你有什麼想法如何解決這個問題? – XN16 2012-08-17 20:18:57

+0

根據您的要求更改了代碼。 – 2012-08-17 20:21:25

5

在服務層的方法,這將是負責做兩件事情:

  1. 打電話給你的加密層哈希密碼(不加密的話)
  2. 調用您的用戶存儲庫以將用戶實體持久化到具有散列密碼的數據庫中

控制器的動作當然會與服務層交談。

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)