我想學習使用哈希和鹽漬保存數據庫密碼的密碼學,所以我決定做一個登錄系統嘗試實現這個系統。PBKDF2鹽醃和散列
我的數據庫由
- 用戶ID INT PK
- 用戶名VARCHAR(250)
- 鹽VARBINARY(64)
- 密碼VARBINARY(64) 的
- RegDate 日期時間
- 電子郵件爲varchar(250)
我使用PBKDF2,但似乎這不是一個散列/鹽析法,它是什麼,如果它是不?
如果是的話我是這麼做的嗎?
我的鑰匙
private const int SALT_SIZE = 64;
private const int KEY_SIZE = 64;
插入數據到數據庫
public static void RegisterMe(string _username, string _password, string _email)
{
using (var cn = new SqlConnection(User.strcon))
{
string _sqlins = @"
INSERT INTO
[User]
([Username],[Salt],[Password],[RegDate], [Email])
VALUES
(@Username, @Salt, @Password, CURRENT_TIMESTAMP, @Email)";
var cmd = new SqlCommand(_sqlins, cn);
cn.Open();
using (var deriveBytes = new Rfc2898DeriveBytes(_password, SALT_SIZE))
{
byte[] salt = deriveBytes.Salt;
byte[] key = deriveBytes.GetBytes(KEY_SIZE);
// save salt and key to database
cmd.Parameters.AddWithValue("@Username", _username);
cmd.Parameters.AddWithValue("@Password", key);
cmd.Parameters.AddWithValue("@Salt", salt);
cmd.Parameters.AddWithValue("@Email", _email);
}
cmd.ExecuteNonQuery();
}
}
檢查,如果用戶是有效
public bool IsValid(string _email, string _password)
{
using (var cn = new SqlConnection(strcon))
{
byte[] salt = { }, key = { };
string _sql = @"
SELECT
SALT,
[Password],
UserID
FROM
[User]
WHERE [Email] = @email";
SqlCommand cmd = new SqlCommand(_sql, cn);
cmd.Parameters.AddWithValue("@email", _email);
cn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
salt = reader.GetSqlBytes(0).Value;
key = reader.GetSqlBytes(1).Value;
reader.Dispose();
cmd.Dispose();
using (var deriveBytes = new Rfc2898DeriveBytes(_password, salt))
{
byte[] newKey = deriveBytes.GetBytes(KEY_SIZE); // derive a 20-byte key
return newKey.SequenceEqual(key);
}
}
else
{
reader.Dispose();
cmd.Dispose();
return false;
}
}
}
我的系統工作正常,它以字節爲單位將數據設置到數據庫中,如果用戶輸入正確的密碼,則返回true。但這是正確的方式嗎?這是甚至哈希/醃製?
我不是很熟悉使用PBKDF2,但從它的外觀我認爲*你是正確的,你實際上沒有哈希密碼。嘗試閱讀此MSDN文檔(http://msdn.microsoft.com/zh-cn/library/system.security.cryptography.rfc2898derivebytes.aspx),其中顯示了一些示例用法,但是這是使用對稱加密。散列是不對稱的,所以你應該永遠不能在原始明文被散列後得到它。 –
@martin_costello我認爲它是哈希密碼。它不使用對稱加密PBKDF2基於HMAC,而不是密碼。散列不是不對稱的,但它確實是一種方式。我非常熟悉PBKDF2。 –
@owlstead我的意思是說MSDN的例子是對稱的。 –