注册客户端和密码

问题描述 投票:0回答:1

我正在使用此代码在我的应用程序中注册客户端,

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();
}

我的问题是如何加密字段密码?

c#
1个回答
0
投票

每个人都说的是正确的,优良做法是哈希密码而不是加密密码。

以下是您如何使用它的方法。

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的链接

© www.soinside.com 2019 - 2024. All rights reserved.