存储哈希值

时间:2012-04-22 20:19:46

标签: c# linq authentication hash salt

有没有办法为这个哈希方法存储salt?我不知道怎么做?

感谢。

    public void AddStudent(Student student)
    { 
        student.StudentID = (++eCount).ToString();
        student.Salt = GenerateSalt();
        byte[] passwordHash = Hash(student.Password, student.Salt);
        student.Password = Convert.ToBase64String(passwordHash);
        student.TimeAdded = DateTime.Now;
        students.Add(student);
    }

1 个答案:

答案 0 :(得分:1)

这应该与你想要的一致。不确定这些学生的存储位置,但也可能需要更改。

[DataMember(Name = "StudentID")]
public string StudentID { get; set; }
[DataMember(Name = "FirstName")]
public string FirstName { get; set; }
[DataMember(Name = "LastName")]
public string LastName { get; set; }
[DataMember(Name = "Password")]
public string Password;
[DataMember(Name = "Salt")]
public byte[] Salt;

protected RNGCryptoServiceProvider random = new RNGCryptoServiceProvider();

public byte[] GenerateSalt()
{
    byte[] salt = new byte[10];
    random.GetNonZeroBytes(salt);
    return salt;
} 

public static byte[] Hash(string value, byte[] salt)
{
    return Hash(Encoding.UTF8.GetBytes(value), salt);
}

public static byte[] Hash(byte[] value, byte[] salt)
{
    byte[] saltedValue = value.Concat(salt).ToArray();

    return new SHA256Managed().ComputeHash(saltedValue);
}

public void AddStudent(Student student)
{
    byte[] salt = GenerateSalt();

    student.StudentID = (++eCount).ToString();
    byte[] passwordHash = Hash(student.Password, salt);
    student.Salt = salt;
    student.Password = Convert.ToBase64String(passwordHash);
    student.TimeAdded = DateTime.Now;
    students.Add(student);
}