public string CreateSalt(int size)
{
var rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
var buff = new byte[size];
rng.GetBytes(buff);
return Convert.ToBase64String(buff);
}
public string GenerateSHA256Hash(String input, String salt)
{
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(input + salt);
System.Security.Cryptography.SHA256Managed sha256hashstring =
new System.Security.Cryptography.SHA256Managed();
byte[] hash = sha256hashstring.ComputeHash(bytes);
return Convert.ToBase64String(hash);
}
public void Submit1_click(object sender, EventArgs r)
{
try
{
String salt = CreateSalt(10);
String hashedpassword = GenerateSHA256Hash(password1.Text, salt);
string MyConString = "SERVER=localhost;DATABASE=mydb;UID=root;PASSWORD=abc123;";
MySqlConnection connection = new MySqlConnection(MyConString);
string cmdText = "INSERT INTO authentication(agentlogin ,password ,question ,answer)VALUES ( @login, @pwd, @question, @answer)";
MySqlCommand cmd = new MySqlCommand(cmdText, connection);
cmd.Parameters.AddWithValue("@login", labeluname.Text);
cmd.Parameters.AddWithValue("@pwd", hashedpassword);
cmd.Parameters.AddWithValue("@question", ddlquestion.Text);
cmd.Parameters.AddWithValue("@answer", txtanswer.Text);
connection.Open();
int result = cmd.ExecuteNonQuery();
connection.Close();
lblmsg.Text = "Registered succesfully";
lblmsg.ForeColor = System.Drawing.Color.Green;
Response.Redirect("index.aspx");
}
catch (Exception)
{
Console.Write("not entered");
lblmsg.Text = "Registration failed!";
lblmsg.ForeColor = System.Drawing.Color.Red;
Response.Redirect("index.aspx");
}
}
我已经从上面得到了完全加密的密码,但现在我无法使用输入的密码登录。当登录时,如何取消加盐密码?我想我可以使用与加密相同的方法来解密它,但是加盐不会返回相同的值。 以下是验证页面上的代码
public string GenerateSHA256Hash(String input)
{
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(input);
System.Security.Cryptography.SHA256Managed sha256hashstring =
new System.Security.Cryptography.SHA256Managed();
byte[] hash = sha256hashstring.ComputeHash(bytes);
return Convert.ToBase64String(hash);
}
public void Login_click(object sender, EventArgs r)
{
String hashedpassword = GenerateSHA256Hash(txtpassword.Text);
string MyConString = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
MySqlConnection con = new MySqlConnection(MyConString);
MySqlCommand cmd = new MySqlCommand("select * from authentication where agentlogin=@username and password=@word", con);
cmd.Parameters.AddWithValue("@username", txtusername.Text);
cmd.Parameters.AddWithValue("@word", hashedpassword);
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
if (dt.Rows.Count > 0)
{
Session["id"] = txtusername.Text;
Response.Redirect("calendar.aspx");
Session.RemoveAll();
}
else
{
lblmsg.Text = "Credential doesn't match!";
lblmsg.ForeColor = System.Drawing.Color.Red;
}
}