c# - 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");
}
}
解决方案
查看string decusr = AesCrypt.Decrypt(encusr);
并在该行上使用断点以查看encusr
该点的值。
您正在将一个包含 SQL 查询的字符串传递给该AesCrypt.Decrypt
方法,该方法期望获得一个要解密的加密值。您可能希望它处理运行该查询的结果,而不是查询本身。
其他提示:
MySqlConnection
并且MySqlCommand
都是,IDisposable
所以每个都应该在一个using
块中。完成此操作后,您无需担心关闭连接,因为退出 using 块将释放连接,该连接将调用 Close。请注意,即使您的代码在块内引发异常,它也会关闭它。- 如果您使用字符串连接来构造查询,它很容易受到 SQL 注入攻击(和其他问题):请改用 SQL 参数。
- 正如评论中的其他人所提到的,存储密码的哈希而不是对其进行加密是一种很好的做法。加密是一个双向过程,它允许某人通过解密来找出密码。哈希是一种单向但可重复的过程。您无需尝试解密存储的密码,而是创建输入密码的散列并检查该散列是否与实际密码的存储散列相同。但请确保使用盐渍哈希。
推荐阅读
- azure-functions - 在 Azure Functions 中绑定到 json 有效负载和 http 触发器的标头
- airflow - 任务在排队且未恢复时在 Airflow 中移动到已移除状态
- javascript - 使用javascript jquery将html附加到具有指定类的按钮最近的div
- node.js - Amazon SES verifyEmailIdentity 未发送电子邮件
- swagger - Swagger 是否可以为 POST 和 PATCH 显示不同的模型视图,即一次写入属性?
- postgresql - 将 DialogflowChatbot 与 PostgreSQL 数据库连接
- visual-studio - USQL 脚本中的联接
- machine-learning - keras 中的 UpSampling2D 和 Conv2DTranspose 函数有什么区别?
- excel - 根据另一个空白单元格创建值的汇总列表?
- linux - 多个 SRCDIR 文件夹,用于使用 makefile 进行编译