c# - registering clients and password
问题描述
I'm registering clients in my application using this code,
string query= "INSERT INTO clientes (username,morada, sexo, telemovel, nif,password,email) " +
"VALUES(@username,@morada,@sexo,@telemovel,@nif,@password,@email)";
if(a.open_connection())
{
MySqlCommand cmd = new MySqlCommand(query, a.connection);
cmd.Parameters.AddWithValue("@username", textBox1.Text);
cmd.Parameters.AddWithValue("@morada", textBox2.Text);
cmd.Parameters.AddWithValue("@sexo", comboBox1.Text);
cmd.Parameters.AddWithValue("@telemovel", maskedTextBox2.Text);
cmd.Parameters.AddWithValue("@nif", maskedTextBox1.Text);
cmd.Parameters.AddWithValue("@email", textBox7.Text);
cmd.Parameters.AddWithValue("@password", textBox4.Text);
cmd.ExecuteNonQuery();
a.close_connection();
}
my question is how can i encrypt the field password?
解决方案
每个人都说的是正确的,散列密码而不是加密密码是一种很好的做法。
这是您如何使用它的方法。
private const int SHAVALUE = 16; // Change this number to whatever you want. It's like your key
private const int CB = 20; // You can change this two if you want (For extra security, maybe)
private static string GetPasswordReadyForDatabaseStorage(string password)
{
var salt = new byte[SHAVALUE];
//Create the salt value with a cryptographic PRNG:
new RNGCryptoServiceProvider().GetBytes(salt);
//Create the Rfc2898DeriveBytes and get the hash value:
var pbkdf2 = new Rfc2898DeriveBytes(password, salt, 10000);
var hash = pbkdf2.GetBytes(CB);
//Combine the salt and password bytes for later use:
var hashBytes = new byte[SHAVALUE+CB];
Array.Copy(salt, 0, hashBytes, 0, SHAVALUE);
Array.Copy(hash, 0, hashBytes, SHAVALUE, CB);
//Turn the combined salt+hash into a string for storage
return Convert.ToBase64String(hashBytes);
}
private static bool VerifyPassword(string passwordUserEntered)
{
/* Fetch the stored value */
string getPasswordHash = savedPasswordHash;//<--- Get the hash password from the database and place it here.
/* Extract the bytes */
var hashBytes = Convert.FromBase64String(getPasswordHash);
/* Get the salt */
var salt = new byte[SHAVALUE];
Array.Copy(hashBytes, 0, salt, 0, SHAVALUE);
/* Compute the hash on the password the user entered */
var pbkdf2 = new Rfc2898DeriveBytes(passwordUserEntered, salt, 10000);
var hash = pbkdf2.GetBytes(CB);
/* Compare the results */
for (int i = 0; i < CB; i++)
if (hashBytes[i + SHAVALUE] != hash[i])
{
return false;
}
return true;
}
您可以更进一步,使用 SecureStrings 代替字符串参数。希望这可以帮助!
这是我引用此代码的链接 https://stackoverflow.com/a/10402129/251311
推荐阅读
- python - 如何遍历线性回归的斜率并检索参数和 p 值?
- javascript - 试图将嵌套子数组对象中的元素映射到 HTML 表格中的单元格,不确定如何到达最深的子数组
- cordova - Whatsapp 消息到不在通讯录上的号码
- c++ - Windows 替代品的全局鼠标按钮按下捕获(WH_MOUSE_LL 似乎落后于鼠标)
- python - 如何在 docker 中为 python 设置 selenium?
- c# - 如何从嵌套属性中获取值?
- android - 减少超过 16,000 行文本的 StaticLayout 初始化时间
- mqtt - MQTTNet UseApplicationMessageReceivedHandler 未触发
- java - Spring JPA:在@JoinTable 中插入数据
- flutter - 如何使用 RawMaterialButton 中的 onLongPressed 属性连续增加或减少值?