首页 > 解决方案 > AES 解密和加密

问题描述

我已合并此代码来加密我的数据。不幸的是,总是有这个错误:

输入不是有效的 Base 64 字符串,因为它包含非 Base 64 字符、两个以上的空格或空格中的无效字符。

这是我的代码 -->

    public static string IV = "abababababababab";  // 16 chars = 128 bytes
    public static string Key = "abababababababababababababababab";   // 32 chars = 256 bytes
    public static string Encrypt(string decrypted)
    {
        byte[] textbytes = ASCIIEncoding.ASCII.GetBytes(decrypted);
        AesCryptoServiceProvider encdec = new AesCryptoServiceProvider();
        encdec.BlockSize = 128;
        encdec.KeySize = 256;
        encdec.Key = ASCIIEncoding.ASCII.GetBytes(Key);
        encdec.IV = ASCIIEncoding.ASCII.GetBytes(IV);
        encdec.Padding = PaddingMode.PKCS7;
        encdec.Mode = CipherMode.CBC;

        ICryptoTransform icrypt = encdec.CreateEncryptor(encdec.Key, encdec.IV);

        byte[] enc = icrypt.TransformFinalBlock(textbytes, 0, textbytes.Length);
        icrypt.Dispose();

        return Convert.ToBase64String(enc);
    }

    public static string Decrypt(string encrypted)
    {
        byte[] encbytes = Convert.FromBase64String(encrypted);
        AesCryptoServiceProvider encdec = new AesCryptoServiceProvider();
        encdec.BlockSize = 128;
        encdec.KeySize = 256;
        encdec.Key = ASCIIEncoding.ASCII.GetBytes(Key);
        encdec.IV = ASCIIEncoding.ASCII.GetBytes(IV);
        encdec.Padding = PaddingMode.PKCS7;
        encdec.Mode = CipherMode.CBC;

        ICryptoTransform icrypt = encdec.CreateDecryptor(encdec.Key, encdec.IV);

        byte[] dec = icrypt.TransformFinalBlock(encbytes, 0, encbytes.Length);
        icrypt.Dispose();

        return ASCIIEncoding.ASCII.GetString(dec);
    }

这是我的登录表单 -->

        private void buttonlogin_Click(object sender, EventArgs ex)
    {
        if (textboxusername.Text.Length < 2 || textboxpassword.Text.Length < 4)
        {
            FormMsbOk.Show("Username or Password is too short!","Ok");
        }
        else
        {
            MySqlConnection con;
            con = new MySqlConnection(myConnectionString);
            try
            {
                con.Open();
                string exists = $"CREATE TABLE IF NOT EXISTS `userlogin`.`userlogin` " +
                $"( `id` INT NOT NULL AUTO_INCREMENT , `username` VARCHAR(64)" +
                $" NOT NULL , `password` VARCHAR(64) NOT NULL , `prename` VARCHAR(64)" +
                $" NOT NULL , `surname` VARCHAR(64) NOT NULL , `emailadress` VARCHAR(64)" +
                $" NOT NULL , PRIMARY KEY (`id`)) ENGINE = InnoDB;";
                MySqlCommand cmd = new MySqlCommand(exists, con);
                cmd.ExecuteNonQuery();

                string user = AesCrypt.Encrypt(textboxusername.Text);
                string pass = AesCrypt.Encrypt(textboxpassword.Text);
                string encusr = $"SELECT * FROM userlogin WHERE username='{user}';";
                string encpass = $"SELECT * FROM userlogin WHERE password='{pass}';";

                string decusr = AesCrypt.Decrypt(encusr);
                string decpass = AesCrypt.Decrypt(encpass);

                if (decusr == textboxusername.Text && decpass == textboxpassword.Text)
                {
                    FormMsbOk.Show("You logged in successfully as user: " + textboxusername.Text, "Ok");
                    con.Close();
                    this.Hide();
                    var main = new FormMain();
                    main.Closed += (s, args) => this.Close();
                    main.Show();
                }
                else
                {
                    textboxusername.Clear();
                    textboxpassword.Clear();
                    FormMsbOk.Show("Error Username or password is wrong!", "Ok");
                }
            }
            catch (Exception nocon)
            {
                textboxusername.Clear();
                textboxpassword.Clear();
                FormMsbOk.Show("Can not open connection! " + nocon.Message,"Ok");
            }

这是我的注册表-->

private void buttonregister_Click(object sender, EventArgs e)
    {
        if (textboxusername.Text.Length < 2 || textboxpassword.Text.Length < 4)
        {
            FormMsbOk.Show("Username or Password is too short! " +
                "The minimum for the user name is 2 characters and for " +
                "the password is 4 characters. ", "Ok");
        }
        else
        {
            MySqlConnection con;
            con = new MySqlConnection(myConnectionString);
            try
            {
                con.Open();
                string exists = $"CREATE TABLE IF NOT EXISTS `userlogin`.`userlogin` " +
                $"( `id` INT NOT NULL AUTO_INCREMENT , `username` VARCHAR(64)" +
                $" NOT NULL , `password` VARCHAR(64) NOT NULL , `prename` VARCHAR(64)" +
                $" NOT NULL , `surname` VARCHAR(64) NOT NULL , `emailadress` VARCHAR(64)" +
                $" NOT NULL , PRIMARY KEY (`id`)) ENGINE = InnoDB;";
                MySqlCommand emdexists = new MySqlCommand(exists, con);
                emdexists.ExecuteNonQuery();
                string encusr = AesCrypt.Encrypt(textboxusername.Text);
                string encpass = AesCrypt.Encrypt(textboxpassword.Text);
                string encprename = AesCrypt.Encrypt(textboxprename.Text);
                string enclastname = AesCrypt.Encrypt(textboxlastname.Text);
                string encemail = AesCrypt.Encrypt(textboxemail.Text);
                string insert = $"INSERT INTO `userlogin`.`userlogin` " +
                    $"(`username`, `password`, `prename`, `surname`, `emailadress`) " +
                    $"VALUES ('" + encusr + "', '" + encpass + "', '" + encprename + "'," +
                    " '" + enclastname + "', '" + encemail + "');";
                MySqlCommand cmdinsert = new MySqlCommand(insert, con);
                cmdinsert.ExecuteNonQuery();
                con.Close();
                FormMsbOk.Show("Registriert", "Ok");
                textboxusername.Clear();
                textboxpassword.Clear();
                textboxprename.Clear();
                textboxlastname.Clear();
                textboxrepeat.Clear();
                textboxemail.Clear();
            }
            catch (Exception nocon)
            {
                FormMsbOk.Show("Can not open connection! " + nocon.Message, "Ok");
            }
        }

标签: c#mysqlencryptionutf-8ascii

解决方案


查看string decusr = AesCrypt.Decrypt(encusr);并在该行上使用断点以查看encusr该点的值。

您正在将一个包含 SQL 查询的字符串传递给该AesCrypt.Decrypt方法,该方法期望获得一个要解密的加密值。您可能希望它处理运行该查询的结果,而不是查询本身。

其他提示:

  1. MySqlConnection并且MySqlCommand都是,IDisposable所以每个都应该在一个using块中。完成此操作后,您无需担心关闭连接,因为退出 using 块将释放连接,该连接将调用 Close。请注意,即使您的代码在块内引发异常,它也会关闭它。
  2. 如果您使用字符串连接来构造查询,它很容易受到 SQL 注入攻击(和其他问题):请改用 SQL 参数。
  3. 正如评论中的其他人所提到的,存储密码的哈希而不是对其进行加密是一种很好的做法。加密是一个双向过程,它允许某人通过解密来找出密码。哈希是一种单向但可重复的过程。您无需尝试解密存储的密码,而是创建输入密码的散列并检查该散列是否与实际密码的存储散列相同。但请确保使用盐渍哈希

推荐阅读