,而不是直接存儲在cookie中的用戶名和密碼,存儲用戶名和密碼的哈希,並在cookie鹽,那麼當你驗證cookie時,檢索給定用戶名的密碼,重新創建與密碼和相同的鹽的散列並比較它們。
創建哈希與將密碼和salt值一起存儲在字符串中一樣簡單,將字符串轉換爲字節數組,計算字節數組的哈希(使用MD5或任何您喜歡的)並轉換生成的哈希到一個字符串(可能通過base64編碼)。
下面是一些示例代碼:
// Create a hash of the given password and salt.
public string CreateHash(string password, string salt)
{
// Get a byte array containing the combined password + salt.
string authDetails = password + salt;
byte[] authBytes = System.Text.Encoding.ASCII.GetBytes(authDetails);
// Use MD5 to compute the hash of the byte array, and return the hash as
// a Base64-encoded string.
var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] hashedBytes = md5.ComputeHash(authBytes);
string hash = Convert.ToBase64String(hashedBytes);
return hash;
}
// Check to see if the given password and salt hash to the same value
// as the given hash.
public bool IsMatchingHash(string password, string salt, string hash)
{
// Recompute the hash from the given auth details, and compare it to
// the hash provided by the cookie.
return CreateHash(password, salt) == hash;
}
// Create an authentication cookie that stores the username and a hash of
// the password and salt.
public HttpCookie CreateAuthCookie(string username, string password, string salt)
{
// Create the cookie and set its value to the username and a hash of the
// password and salt. Use a pipe character as a delimiter so we can
// separate these two elements later.
HttpCookie cookie = new HttpCookie("YourSiteCookieNameHere");
cookie.Value = username + "|" + CreateHash(password, salt);
return cookie;
}
// Determine whether the given authentication cookie is valid by
// extracting the username, retrieving the saved password, recomputing its
// hash, and comparing the hashes to see if they match. If they match,
// then this authentication cookie is valid.
public bool IsValidAuthCookie(HttpCookie cookie, string salt)
{
// Split the cookie value by the pipe delimiter.
string[] values = cookie.Value.Split('|');
if (values.Length != 2) return false;
// Retrieve the username and hash from the split values.
string username = values[0];
string hash = values[1];
// You'll have to provide your GetPasswordForUser function.
string password = GetPasswordForUser(username);
// Check the password and salt against the hash.
return IsMatchingHash(password, salt, hash);
}
@Erik我包括所有這些在一個類..如何使用它們在我的按鈕點擊? – 2010-07-28 18:00:16
我假設你的意思是你的登錄按鈕:在這種情況下,只是讓你平時會,請致電用戶名,密碼和鹽「CreateAuthCookie」的方法傳遞(這是真的只是任意字符串的用戶名和密碼,只要因爲每個方法調用都使用相同的方法) - 然後按照該方法返回的cookie進行操作。 – 2010-07-28 18:01:49
當談到時間,看看用戶已經登錄,您剛纔找到的名稱(「YourSiteCookieNameHere」)您的Cookie,並稱之爲「IsValidAuthCookie」方法中的值該cookie存儲在實際的認證數據進行比較,您的數據庫。不要忘記使用相同的鹽。 – 2010-07-28 18:02:52