简体   繁体   English

散列密码算法和程序的实际运行

[英]Hashing password algorithm and actual running of the program

I am new in the C# programming and try to create login form in WPF using C# and MySQL database. 我是C#编程的新手,并尝试使用C#和MySQL数据库在WPF中创建登录表单。 When I run my WPF and try to insert data I am getting error on this line: 当我运行WPF并尝试插入数据时,在此行出现错误:

using (var cmd = new MySqlCommand("Select salt From niki where user_name = @username"))
{
    cmd.Parameters.AddWithValue("@username", username);
    salt = cmd.ExecuteScalar() as string;
}

The error is connection must be valid and open. 错误是连接必须有效且打开。 Do you have any clue where can be the problem? 您有什么线索可能出问题吗?

Guys this is the whole code where I just replace the sensitive data fields with unreal, Although I change the things i am still getting the error. 伙计们,这是整个代码,我只是用虚幻的内容替换了敏感数据字段,尽管我更改了内容,但仍然遇到错误。 Can you identify where the problem is comming from? 您能确定问题出在哪里吗?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Security.Cryptography;
using System.Security.Authentication;
using System.Security.Permissions;
using System.Security.AccessControl;
using System.Security.Policy;
using System.Security.Principal;
using System.Security.Util;




namespace ECBSRecruitmentAgencySoftware
{
    public partial class LogIn : Form
    {

        public LogIn()
        {

            InitializeComponent();

        }

    static byte[] GenerateSaltedHash(string plainText, string salt)
    {
       HashAlgorithm algorithm = new SHA256Managed();

       byte[] plainTextBytes = System.Text.Encoding.Unicode.GetBytes(plainText);
       byte[] saltBytes = Convert.FromBase64String(salt);

       byte[] plainTextWithSaltBytes = new byte[plainTextBytes.Length + saltBytes.Length];
       saltBytes.CopyTo(plainTextWithSaltBytes, 0);
       plainTextBytes.CopyTo(plainTextWithSaltBytes, salt.Length); 

       byte[] hash = algorithm.ComputeHash(plainTextWithSaltBytes);

       return hash;
    }

        public bool tryLogin(string username , string password)
        {
             using (var con = new MySqlConnection("host=tara.rdb.superhosting.bg;user=sozopouk;password=27051996;database=sozopouk_test2;"))
             {
                 con.Open();

                 var salt = string.Empty;

                 using (var cmd = new MySqlCommand("Select salt From niki where user_name = @username"))
                 {
                     cmd.Parameters.AddWithValue("@username", username);

                     salt = cmd.ExecuteScalar() as string;
                 }

                 if (string.IsNullOrEmpty(salt)) return false;

                 var hashedPassword = GenerateSaltedHash(password, salt);

                 using (var cmd = new MySqlCommand("Select * FROM niki WHERE user_name = @username and user_password = @password"))
                 {
                    cmd.Parameters.AddWithValue("@username", username);
                    cmd.Parameters.AddWithValue("@password", hashedPassword);

                    using (var reader = cmd.ExecuteReader())
                    {
                         return reader.Read();
                    }
                 }
             }
        }

        private void button1_Click(object sender, EventArgs e)
        {
             if (tryLogin(user.Text, pass.Text) == true)
            {
                MainScreen F2 = new MainScreen();
                F2.Show();
                this.Hide();
            }

             else MessageBox.Show("Wrong details!");

        }        
        }


}

Do you mean that I have to update : 您是说我必须更新:

 using (var con = new MySqlConnection("host=tara.rdb.superhosting.bg;user=sozopouk;password=27051996;database=sozopouk_test2;"))
                 {
                     con.Open();

                     var salt = string.Empty;

                     using (var cmd = new MySqlCommand("Select salt From niki where user_name = @username"))
                     {
                         cmd.Parameters.AddWithValue("@username", username);

                         salt = cmd.ExecuteScalar() as string;
                     }
enter code here
enter code here

With the code that you produce? 用您产生的代码? If yes how am I actually connect to my MySQL database? 如果是,我实际上如何连接到我的MySQL数据库?

Well, before any attempt to read or write to the database you should open a connection, then issue commands. 好吧,在尝试读取或写入数据库之前,您应该打开一个连接,然后发出命令。

using (MySqlConnection cn = GetConnection())
{
    cn.Open();
    // create the command and link it to the connection
    using (var cmd = new MySqlCommand("Select salt From niki where user_name = @username", cn)) 
    { 
        cmd.Parameters.AddWithValue("@username", username); 
        salt = cmd.ExecuteScalar() as string; 
    }
} 

public MySqlConnection GetConnection()
{
     MySqlConnection cn = new MySqlConnection("Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;");
     return cn;
}

EDIT: The missing piece of the puzzle is here: 编辑:拼图的缺失部分在这里:

MySqlCommand cmd = MySqlCommand("your_query_text", cn)

have you got a connection? 你有联系吗? try something like 尝试类似

        using (MySqlConnection connection = new MySqlConnection(connectionString))
        {
            connection.Open();
            using (MySqlCommand command = new MySqlCommand("Select salt From niki where user_name = @username", connection))
            {
                command.CommandType = CommandType.Text;
                command.Parameters.AddWithValue("@username", username);
                salt = cmd.ExecuteScalar() as string;
            }                
        }

Edit with your updated post you are not using the connection, you need in the constructor for the MySqlCommand 使用更新后的帖子进行编辑 ,您不使用连接,需要在MySqlCommand的构造函数中

using (MySqlCommand command = new MySqlCommand(Command, Connection))
{
}

or else something like 否则像

command.Connection = connection;

Edit 2 if you replace your database code with the code below do you still have issues? 编辑2如果您用下面的代码替换数据库代码,您仍然遇到问题吗?

             using (var con = new MySqlConnection("host=tara.rdb.superhosting.bg;user=sozopouk;password=27051996;database=sozopouk_test2;"))
             {
                 con.Open();

                 var salt = string.Empty;

                 using (var cmd = new MySqlCommand("Select salt From niki where user_name = @username", con))
                 {
                     cmd.Parameters.AddWithValue("@username", username);

                     salt = cmd.ExecuteScalar() as string;
                 }

                 if (string.IsNullOrEmpty(salt)) return false;

                 var hashedPassword = GenerateSaltedHash(password, salt);

                 using (var cmd = new MySqlCommand("Select * FROM niki WHERE user_name = @username and user_password = @password", con))
                 {
                    cmd.Parameters.AddWithValue("@username", username);
                    cmd.Parameters.AddWithValue("@password", hashedPassword);

                    using (var reader = cmd.ExecuteReader())
                    {
                         return reader.Read();
                    }
                 }
             }

There are a couple issues here. 这里有几个问题。

The first is that you don't appear to actually instantiate a MySqlConnection object, which is necessary to establish the connection. 第一个是您似乎没有实际实例化MySqlConnection对象,这对于建立连接是必需的。

Look at: http://zetcode.com/db/mysqlcsharptutorial/ 查看:http: //zetcode.com/db/mysqlcsharptutorial/

for a bit of info on how to work with MySql in C# 有关如何在C#中使用MySql的信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM