我正在开发一个需要登录表单、用户和密码保存在 SQL Server 数据库中的 C# 应用程序。
我使用我的CodePass
函数来编码密码,我已经添加了一个用户,并且之前它是我的数据库的编码密码(用户、密码和登录角色保存在数据库中)
现在当我像这样调用我的 doLogin 函数时
doLogin("Arashdn","123");
它返回 0(错误的用户或密码) 在调试应用程序后,我发现hash
(用于保持从数据库读取加密密码的变量)持有 123 个未加密密码。
问题可能是什么?
这是我的代码:
public class DB
{
public static string constr = "Server=localhost;Database=University;
Integrated Security=true;MultipleActiveResultSets=True;";
public static string userTable = "Users", userPassword = "Passwd",
userName = "UserID", loginRole = "Role";
}
public class login
{
public int doLogin(string user, string pass)
{
string role="0";
SqlConnection conn = new SqlConnection(DB.constr);
try
{
conn.Open();
SqlCommand my_cm = conn.CreateCommand();
SqlDataReader dbread1;
my_cm.CommandText = "Select " + DB.userPassword + " from " +
DB.userTable + " WHERE " + DB.userName + "=" + user;
dbread1 = my_cm.ExecuteReader();
string hash="";
while (dbread1.Read())
{
hash = dbread1[0].ToString();
}
if (CodePass(user, pass) == hash)
{
SqlCommand my_cm2 = conn.CreateCommand();
SqlDataReader dbread2;
my_cm2.CommandText = "Select " + DB.loginRole + " from " +
DB.userTable + " WHERE " + DB.userName + "=" + user;
dbread2 = my_cm2.ExecuteReader();
while (dbread2.Read())
{
role = dbread2[0].ToString();
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (conn.State == System.Data.ConnectionState.Open)
conn.Close();
}
return int.Parse(role);
}
public string CodePass(string user, string pass)
{
System.Security.Cryptography.SHA1CryptoServiceProvider sha =
new SHA1CryptoServiceProvider();
return System.Text.Encoding.ASCII.GetString(
sha.ComputeHash(System.Text.Encoding.ASCII.GetBytes(user + pass)));
}
}
谢谢