所以我遇到了这个脚本的问题。我在我的项目中创建了一个新类,它名为AesCryp.cs
,它带有加密和解密方法。这是脚本:
class AesCryp
{
public static string IV = "xxxxxxxxxxxxxxxx";
public static string Key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
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);
}
}
我在创建新帐户时已经创建了它,它将加密密码并将其插入数据库。这是注册脚本:
public bool Register(string user, string pass)
{
string query = $"INSERT INTO users (ID, Username, Password) VALUES ('', '{user}', '{pass}');";
try
{
if (OpenConnection())
{
MySqlCommand cmd = new MySqlCommand(query, db);
try
{
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
return false;
}
}
else
{
db.Close();
return false;
}
}
catch (Exception ex)
{
db.Close();
return false;
}
}
这是SignUp按钮脚本:
private void SignUp_Click(object sender, EventArgs e)
{
string user = usernameTxt.Text;
string pass = AesCryp.Encrypt(passwordTxt.Text);
if(Register(user, pass))
{
MessageBox.Show($"User {user} has been created!");
}
else
{
MessageBox.Show($"User {user} has not been created!");
}
}
然而,我真的很困惑我将如何制作它,以便在我尝试登录时解密数据库中的加密密码。这是我的登录脚本,没有任何解密(因为我不完全确定我会怎么做)
public bool IsLogin(string user, string pass)
{
string query = $"SELECT * FROM users WHERE Username='{user}' AND Password='{pass}';";
try
{
if (OpenConnection())
{
MySqlCommand cmd = new MySqlCommand(query, conn);
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
reader.Close();
conn.Close();
return true;
}
else
{
reader.Close();
conn.Close();
return false;
}
}
else
{
conn.Close();
return false;
}
}
catch (Exception ex)
{
conn.Close();
return false;
}
}
这是登录按钮脚本:
private void Login_Click(object sender, EventArgs e)
{
string user = usernameTxt.Text;
string pass = passwordTxt.Text;
if (IsLogin(user, pass))
{
MessageBox.Show($"Welcome {user}!");
}
else
{
MessageBox.Show("Username or password is incorrect!");
}
}
如果有人能帮助我,那就太棒了。谢谢!