0

学校向けのアプリケーションを作成していますが、ユーザー データベースにパスワードを挿入するときにパスワードを暗号化する方法が必要です。C# プログラミング言語でプログラミングしており、データベースの操作に MS サーバー 2008 R2 を使用しています。私は HASH 暗号化を考えています。誰かが私を助けてくれたらうれしいです。

データベースにデータを挿入するための私のコードは次のとおりです。

using (SqlConnection con = new SqlConnection("Data Source=HRC0;Initial Catalog=users;Integrated Security=True")) //MLHIDE
        using (SqlCommand sc = new SqlCommand("if NOT exists (select * from users where UserName = @username) insert into users (userName, password) values(@userName, @password)", con)) 
        {
            con.Open();
            sc.Parameters.AddWithValue("@username", korisnik.Text); 
            sc.Parameters.AddWithValue("@password", pass.Text);   
            int o = sc.ExecuteNonQuery();
            if (o == -1)
            {
                MessageBox.Show(Ulaz.Properties.Resources.Niste_ubačeni_u_bazi_korisničk);
                this.Hide();
                new Registracija().Show();
            }
            else 
            {
                MessageBox.Show(Ulaz.Properties.Resources.Ubačeni_ste_u_bazi);
                con.Close();
                this.Hide();
                new Form1().Show();

             }

そして、これがログインチェック用の私のコードです:

SqlConnection con = new SqlConnection("Data Source=HRC0;Initial Catalog=users;Integrated Security=True");
        SqlCommand cmd = new SqlCommand("select * from users where userName='" + user.Text + "' and password='" + pass.Text + "'", con); //MLHIDE
        con.Open();
        SqlDataReader re = cmd.ExecuteReader();

        if (re.Read())
        {
            ImeUsera = user.Text;
            new UserMode().Show();
            this.Hide();
        }
           else
            {
                this.Hide();
                new LoginFail().Show();
            }
        }

私はいくつかの多言語アドオンを使用したので、彼は私の文字列を「Ulaz.Properties.Resources.」などに変換しました。

4

1 に答える 1

1

テキストの文字列をハッシュするには、次のような関数を使用できます

private string GetHashedText(string inputData)
{ 
    byte[] tmpSource;
    byte[] tmpData;
    tmpSource = ASCIIEncoding.ASCII.GetBytes(inputData);
    tmpData = new MD5CryptoServiceProvider().ComputeHash(tmpSource);
    return Convert.ToBase64String(tmpData);
}

ユーザー入力に適用します。次に、結果をデータベースに保存します。ログイン時に、入力したパスワードにハッシュ関数を再適用し、結果を保存された値と照合します。

したがって、挿入コードで次のように記述します

 sc.Parameters.AddWithValue("@password", GetHashedText(pass.Text));   

そしてあなたの小切手で

 ....
 SqlCommand cmd = new SqlCommand("select * from users where userName=@user and password=@pass", con);
 con.Open();
 cmd.Parameters.AddWithValue("@user",user.Text);
 cmd.Parameters.AddWithValue("@pass", GetHashedText(pass.Text));
 SqlDataReader re = cmd.ExecuteReader();
 if (re.Read())
 .....

ハッシュは元に戻せないため、ハッシュされたテキストから元のパスワードを取得することはできません。ハッシュ関数をテキストに適用し、base64 文字列として保存します。ユーザーがパスワードを忘れた場合は、既知の値にリセットする必要があります。彼に元のパスワードを伝える方法はありません。

ところで、挿入コードのようにチェックでパラメータを使用しないのはなぜですか? 文字列連結を使用して SQL クエリを作成しないでください。急いで仕事を終わらせても

于 2013-06-05T17:08:34.563 に答える