问题描述
我正在尝试将我的哈希密码插入我的数据库。我使用BCrypt函数来散列密码:
I am trying to insert my hashed password into my database. I am using a BCrypt function to hash the password:
#region Password Hash w/ BCrypt
private static string GetRandomSalt()
{
return BCryptHelper.GenerateSalt(12);
}
public static string HashPassword(string password)
{
return BCryptHelper.HashPassword(password, GetRandomSalt());
}
public static bool ValidatePassword(string password, string correctHash)
{
return BCryptHelper.CheckPassword(password, correctHash);
}
#endregion
以下是查询参数的构建:
Here is the building of the query parameters:
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(insert, conn);
// build params
cmd.Parameters.AddWithValue("@FirstName", tbxFname.Text.Trim());
cmd.Parameters.AddWithValue("@LastName", tbxLname.Text.Trim());
cmd.Parameters.AddWithValue("@Email", tbxEmail.Text.Trim());
string password = HashPassword(tbxPassword.Text);
char[] hashedPassword = password.ToCharArray();
cmd.Parameters.AddWithValue("@HashedPassword", hashedPassword);
cmd.Parameters.AddWithValue("@Gender", rbnGender.SelectedValue.Trim());
cmd.Parameters.AddWithValue("@DateOfBirth", tbxDob.Text.Trim());
cmd.Parameters.AddWithValue("@DateCreated", DateTime.Now);
// execute
cmd.ExecuteNonQuery();
//lbl1.Text = "Success";
}
我在表中使用的数据类型是 CHAR(60),我当前返回的错误是:
插入错误:不允许从数据类型nvarchar到二进制的隐式转换。使用CONVERT函数运行此查询。
The datatype I am using in my table is CHAR(60), and the error I am currently returning is:
Insert error: Implicit conversion from data type nvarchar to binary is not allowed. Use the CONVERT function to run this query.
推荐答案
string password = HashPassword(tbxPassword.Text);
cmd.Parameters.AddWithValue("@HashedPassword", password);
通常,我使用二进制数据进行哈希处理,但由于你的BCryptHelper.HashPassword方法返回一个字符串,所以最好坚持使用它。
错误消息可能是因为.NET char数组被视为用于传输到SQL的字节数组 - 因此它假定您正在发送二进制数据而不是字符。将其作为字符串发送应修复该问题。
Normally, I work with binary data for hashes, but since your BCryptHelper.HashPassword method is returning a string, it's probably best to stick with that.
The error message is probably because a .NET char array is treated as a byte array for transfer to SQL - so it assumes you are sending binary data instead of characters. Sending it as a string should fix that.
这篇关于无法将哈希密码插入数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!