-1

我肯定我在这里做错了什么。使用算法的.net 实现,我将密码与用于散列的盐一起散列到数据库中。在验证与现有哈希不匹配的相同密码时。这是我的代码

新条目

byte[] SALT = GetRandomKey();
string password = Convert.ToBase64String((new Rfc2898DeriveBytes(txtPassword.Text, SALT)).GetBytes(20));
Session["test"] = password;
Session["salt"] = Convert.ToBase64String(SALT);

证实

string HASHEDPASSWORD = Session["test"];
string SALT = Session["salt"];
string ouput = Convert.ToBase64String((new Rfc2898DeriveBytes(password, Encoding.Unicode.GetBytes(SALT))).GetBytes(20));
ltrResult.Text = HASHEDPASSWORD.Equals(ouput) ? "EQUAL" : "NOT EQUAL";

获取 RandomKey 方法

byte[] GetRandomKey()
    {
        byte[] secretkey = new Byte[64];
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        rng.GetBytes(secretkey);
        return secretkey;
    }
4

3 回答 3

3

Convert.FromBase64String代替Encoding.Unicode.GetBytes.

于 2011-11-15T10:25:01.767 回答
1

添加项目时使用 Convert.ToBase64String ,检索项目时使用 Encoding.Unicode.GetBytes ......

添加新条目时使用 Encoding.Unicode.GetString 并且您的代码应该可以工作,例如:

private static string GetString(byte[] bytes)
{
    return Encoding.Unicode.GetString(bytes);
}

private static byte[] GetBytes(string value)
{
    return Encoding.Unicode.GetBytes(value);
}

添加

byte[] salt = GetRandomKey();
byte[] hash = new Rfc2898DeriveBytes(txtPassword.Text, salt)).GetBytes(20);
Session["test"] = GetString(hash);
Session["salt"] = GetString(salt);

检查

byte[] hash = GetBytes(Session["test"]);
byte[] salt = GetBytes(Session["salt"]);
byte[] output = new Rfc2898DeriveBytes(password, salt).GetBytes(20);
ltrResult.Text = GetString(hash).Equals(GetString(output)) ? "EQUAL" : "NOT EQUAL";
于 2011-11-15T10:23:26.460 回答
0

您可以将盐存储为会话中的字节数组,以便在字符串和字节之间转换时不会得到任何编码差异:

byte[] SALT = GetRandomKey();
string password = Convert.ToBase64String((new Rfc2898DeriveBytes(txtPassword.Text, SALT)).GetBytes(20));
Session["test"] = password;
Session["salt"] = SALT;

然后要验证给定的密码是否与哈希匹配,请重复相同的过程:

string HASHEDPASSWORD = Session["test"];
byte[] SALT = Session["salt"] as byte[];
string ouput = Convert.ToBase64String((new Rfc2898DeriveBytes(password, SALT)).GetBytes(20));
ltrResult.Text = HASHEDPASSWORD.Equals(ouput) ? "EQUAL" : "NOT EQUAL";
于 2011-11-15T10:29:53.290 回答