注册客户端和密码

时间:2019-03-26 18:14:23

标签: c#

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

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

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

1 个答案:

答案 0 :(得分: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