Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我无法登录,因为我已在数据库中加密了密码_C#_Sql_Encryption_Passwords - Fatal编程技术网

C# 我无法登录,因为我已在数据库中加密了密码

C# 我无法登录,因为我已在数据库中加密了密码,c#,sql,encryption,passwords,C#,Sql,Encryption,Passwords,这是我使用加密方法的注册页面。我加密了密码: protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) { SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionSt

这是我使用加密方法的注册页面。我加密了密码:

protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
            conn.Open();
            string checkuser = "select count(*) from UserData where Username = '" + txtUser.Text + "'";
            SqlCommand scm = new SqlCommand(checkuser, conn);
            int temp = Convert.ToInt32(scm.ExecuteScalar().ToString());
            if (temp == 1) // check if user already exist.
            {
                Response.Write("User already existing");
            }
            conn.Close();
        }
    }
    protected void btn_Registration_Click(object sender, EventArgs e)
    {
        try
        {
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
            conn.Open();
            string insertQuery = "insert into UserData(Username,Firstname,Lastname,Email,Password,CustomerType,DeliveryAddress,Zip,ContactNumber)values(@Username,@Firstname,@Lastname,@Email,@Password,@CustomerType,@DeliveryAddress,@Zip,@ContactNumber)";
            SqlCommand scm = new SqlCommand(insertQuery, conn);
            scm.Parameters.AddWithValue("@Username", txtUser.Text);
            scm.Parameters.AddWithValue("@Firstname", txtFN.Text);
            scm.Parameters.AddWithValue("@Lastname", txtLN.Text);
            scm.Parameters.AddWithValue("@Email", txtEmail.Text);
            scm.Parameters.AddWithValue("@Password", Encrypt(txtPW.Text));
            scm.Parameters.AddWithValue("@CustomerType", RadioButtonList1.SelectedItem.ToString());
            scm.Parameters.AddWithValue("@DeliveryAddress", txtAddress.Text);
            scm.Parameters.AddWithValue("@Zip", txtZip.Text);
            scm.Parameters.AddWithValue("@ContactNumber", txtContact.Text);

            scm.ExecuteNonQuery();
            Session["Contact"]= txtContact.Text;
            Session["Email"] = txtEmail.Text;
            Session["DeliveryAddress"] = txtAddress.Text;
            label_register_success.Text = ("Registration Successful!");
            //Response.Redirect("Home.aspx");
            conn.Close();
        }
        catch (Exception ex)
        {
            Response.Write("Error:" + ex.ToString());
        }
    }
    private string Encrypt(string clearText)
    {
        string EncryptionKey = "MAKV2SPBNI99212";
        byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(clearBytes, 0, clearBytes.Length);
                    cs.Close();
                }
                clearText = Convert.ToBase64String(ms.ToArray());
            }
        }
        return clearText;
    }
这是我使用解密方法的登录代码。在检查密码是否与用户输入的密码匹配之前,我解密了密码:

 protected void btn_Login_Click(object sender, EventArgs e)
    {
        SqlConnection conn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True");
        conn.Open();
        string checkuser = "select count(*) from UserData where Username = '" + txtUser.Text + "'";
        SqlCommand scm = new SqlCommand(checkuser, conn);
        int temp = Convert.ToInt32(scm.ExecuteScalar().ToString());
        conn.Close();
        if (temp == 1)
        {
            conn.Open();
            string checkPassword = "select Password from UserData where Username ='" + txtUser.Text + "'";
            SqlCommand passCom = new SqlCommand(checkPassword, conn);
            string password = passCom.ExecuteScalar().ToString();
            password = Decrypt(password);
            if (password == txtPassword.Text)
            {
                Session["New"] = txtUser.Text;
                Response.Write("<script>alert('Logged In')</script>");
                Response.Redirect("OrderNow.aspx");
            }
            else
            {
                lblcrederror.Text = ("Credentials dont match");
            }

        }
        else
        {
            lblcrederror.Text = ("Credentials dont match");
        }
    }
    private string Decrypt(string cipherText)
    {
        string EncryptionKey = "MAKV2SPBNI99212";
        byte[] cipherBytes = Convert.FromBase64String(cipherText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(cipherBytes, 0, cipherBytes.Length);
                    cs.Close();
                }
                cipherText = Encoding.Unicode.GetString(ms.ToArray());
            }
        }
        return cipherText;
    }
受保护的无效btn\u登录\u单击(对象发送者,事件参数e)
{
SqlConnection conn=newsqlconnection(“数据源='PAULO';初始目录=ShoppingCartDB;集成安全性=True”);
conn.Open();
string checkuser=“从UserData中选择计数(*),其中Username=”+txtUser.Text+”;
SqlCommand scm=新的SqlCommand(检查用户,conn);
int temp=Convert.ToInt32(scm.ExecuteScalar().ToString());
康涅狄格州关闭();
如果(温度==1)
{
conn.Open();
string checkPassword=“从UserData中选择密码,其中Username=”+txtUser.Text+”;
SqlCommand passCom=新的SqlCommand(检查密码,conn);
字符串密码=passCom.ExecuteScalar().ToString();
密码=解密(密码);
if(password==txtPassword.Text)
{
Session[“New”]=txtser.Text;
响应。写入(“警报(‘已登录’)”;
重定向(“OrderNow.aspx”);
}
其他的
{
lblcrederror.Text=(“凭证不匹配”);
}
}
其他的
{
lblcrederror.Text=(“凭证不匹配”);
}
}
私有字符串解密(字符串密文)
{
字符串EncryptionKey=“makv2spnni99212”;
字节[]cipherBytes=Convert.FromBase64String(密文);
使用(Aes encryptor=Aes.Create())
{
Rfc2898DeriveBytes pdb=新的Rfc2898DeriveBytes(加密密钥,新字节[]{0x49,0x76,0x61,0x6e,0x20,0x4d,0x65,0x64,0x76,0x65,0x64,0x76});
encryptor.Key=pdb.GetBytes(32);
encryptor.IV=pdb.GetBytes(16);
使用(MemoryStream ms=new MemoryStream())
{
使用(CryptoStream cs=new CryptoStream(ms,encryptor.CreateDecryptor(),CryptoStreamMode.Write))
{
cs.Write(cipherBytes,0,cipherBytes.Length);
cs.Close();
}
cipherText=Encoding.Unicode.GetString(ms.ToArray());
}
}
返回密文;
}

我错过了什么?请帮忙。我试图输入一个有效的登录名,但它给了我一个错误(Base-64字符数组或字符串的长度无效)。我的密码在数据库中的nvarchar(MAX)上。

您的登录函数需要从数据库中提取用户密码,并用该密钥解密。如果解密的密码与输入的密码匹配,请让他们输入

不过我会使用salted散列,除非您有特定的理由可以查看用户的密码。然后,您只需要将哈希与登录进行比较

从数据库中获取密码后,将其传递给此

private string Decrypt(string cipherText)
{
    string EncryptionKey = "MAKV2SPBNI99212";
    byte[] cipherBytes = Convert.FromBase64String(cipherText);
    using (Aes encryptor = Aes.Create())
{
    Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
    encryptor.Key = pdb.GetBytes(32);
    encryptor.IV = pdb.GetBytes(16);
    using (MemoryStream ms = new MemoryStream())
    {
        using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
        {
            cs.Write(cipherBytes, 0, cipherBytes.Length);
            cs.Close();
        }
        cipherText = Encoding.Unicode.GetString(ms.ToArray());
    }
 }
 return cipherText;
}

然后,如果cipherText=用户输入的密码,请登录。

第一个代码图像。这就是加密方法@user1666620这行-
if(password==txtPassword.Text)
是否应该加密密码文本框,以查看它是否与已加密的保存值匹配?e、 g.
if(password==Encrypt(txtPassword.Text))
请查看已编辑的查询。我已经输入了登录密码@GarethDdo先生,你有个例子吗?你真的会很感激ita的示例解密或相同的盐渍哈希?嗯,两者都有?让我的代码工作的任何东西。呵呵,谢谢先生。我会把这些加在一起,再加上镶嵌的方法。先生,既然我是新来的,你能彻底地指导我吗?请:)