2012-04-22 175 views
0

有沒有一種方法來存儲這個哈希方法的鹽?我不知道該怎麼做?存儲哈希值

謝謝。

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

您可以將它存儲在'byte []'中。什麼是實際問題? – 2012-04-22 20:27:56

+0

在你的學生對象上創建一個新的字段鹽,然後當你生成salt()時,把鹽放在字段中? – Prescott 2012-04-22 20:31:54

+0

對不起im仍然丟失 – 2012-04-22 20:36:59

回答

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

感謝Lordcheeto(順便說一句,奇妙!)我已經更新了我的問題,可能的答案是否看起來正確? – 2012-04-22 21:39:39

+0

我不認爲你需要'byte [] salt = GenerateSalt();'如果數據庫已經是一個字節[]? – 2012-04-22 21:41:27

+0

@KirstyWhite據我所知,它看起來不錯。是的,我只是沒有想太多。 – lordcheeto 2012-04-22 21:42:24