2015-03-13 62 views
0

我想創建一個簡單的asp.net網站,允許用戶註冊和登錄。我已成功地設法將所有數據存儲在數據庫中,並以登錄形式對用戶進行身份驗證。然而,現在我想要做的事情是每當新用戶註冊以MD5格式存儲數據庫中的密碼並匹配哈希以便用戶能夠登錄時。C#加密登錄

這是在寄存器單元,存儲在數據庫中的用戶代碼:

try 
    { 
     SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["AssignmentDBConnectionString"].ConnectionString); 
     conn.Open(); 
     string insertQuery = "insert into [AsTable] ([Username],Email,Password) values (@Username ,@Email, @Password)"; 
     SqlCommand com = new SqlCommand(insertQuery, conn); 
     com.Parameters.AddWithValue("@Username", TextBoxUsername.Text); 
     com.Parameters.AddWithValue("@email", TextBoxEmail.Text); 
     com.Parameters.AddWithValue("@password", TextBoxPass.Text); 

     com.ExecuteNonQuery(); 
     Response.Redirect("Manager.aspx"); 
     Response.Write("Registration Completed"); 

     conn.Close(); 

    } 
    catch (Exception ex) 
    { 
     Response.Write("Error:"+ex.ToString()); 
    } 

這是在說,爲了驗證用戶登錄部分的代碼,他登錄:

conn.Open(); 
     string checkPasswordQuery = "select Password from [AsTable] where Username ='" + TextBoxUsername.Text + "'"; 
     SqlCommand passcom = new SqlCommand(checkPasswordQuery, conn); 
     string password = passcom.ExecuteScalar().ToString().Replace(" ",""); 
     if (password == TextBoxPassword.Text) 
     { 
      Session["New"] = TextBoxUsername.Text; 
      Response.Write("Password is correct"); 
      Response.Redirect("Index.aspx"); 
     } 
     else 
     { 
      Response.Write("Password is not correct"); 
     } 
    } 

    else 
    { 
     Response.Write("Username is not correct"); 
    } 

} 

任何想法如何改變?

+7

**警告**你的第二個例子容易受到sql注入攻擊! – 2015-03-13 12:53:04

+1

使用默認的sql成員資格提供程序而不是自定義代碼 – Ewan 2015-03-13 12:55:08

+1

使用SP和參數查詢。如果不使用'using'語法,我會關閉finally {}塊中的連接。 – Tim 2015-03-13 12:56:13

回答

1

這是我如何處理加密

首先我創建了一個方法來簡單的字符串轉換爲SHA256(我認爲這是比MD5更好)

public string ToSHA256(string value) 
    { 
     SHA256 sha256 = SHA256.Create(); 

     byte[] hashData = sha256.ComputeHash(Encoding.Default.GetBytes(value)); 
     StringBuilder returnValue = new StringBuilder(); 

     for (int i = 0; i < hashData.Length; i++) 
     { 
      returnValue.Append(hashData[i].ToString()); 
     } 

     return returnValue.ToString(); 
    } 

然後

只是改變你的代碼在創建用戶到

try 
{ 
    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["AssignmentDBConnectionString"].ConnectionString); 
    conn.Open(); 
    string insertQuery = "insert into [AsTable] ([Username],Email,Password) values (@Username ,@Email, @Password)"; 
    SqlCommand com = new SqlCommand(insertQuery, conn); 
    com.Parameters.AddWithValue("@Username", TextBoxUsername.Text); 
    com.Parameters.AddWithValue("@email", TextBoxEmail.Text); 
    com.Parameters.AddWithValue("@password", ToSHA256(TextBoxPass.Text)); 

    com.ExecuteNonQuery(); 
    Response.Redirect("Manager.aspx"); 
    Response.Write("Registration Completed"); 

    conn.Close(); 

} 
catch (Exception ex) 
{ 
    Response.Write("Error:"+ex.ToString()); 
} 

然後在檢索密碼

conn.Open(); 
    string checkPasswordQuery = "select Password from [AsTable] where Username ='" + ToSHA256(TextBoxUsername.Text) + "'"; 
    SqlCommand passcom = new SqlCommand(checkPasswordQuery, conn); 
    //string password = passcom.ExecuteScalar().ToString().Replace(" ",""); 
    if (password == ToSHA256(TextBoxPassword.Text)) 
    { 
     Session["New"] = TextBoxUsername.Text; 
     Response.Write("Password is correct"); 
     Response.Redirect("Index.aspx"); 
    } 
    else 
    { 
     Response.Write("Password is not correct"); 
    } 
} 

else 
{ 
    Response.Write("Username is not correct"); 
} 
} 
+0

我將此方法複製並粘貼到註冊文件和登錄文件中,但方法名稱「ToSHA256」變成紅色,並表示並非所有代碼路徑都返回值!我已經包含了使用System.Security.Cryptography; using System.Text; – michalis 2015-03-13 13:17:43

+0

修復...編輯:) 固定方法 – DaProtagonist 2015-03-13 13:24:46

+0

非常感謝..它現在的作品!乾杯!! :d – michalis 2015-03-13 13:40:15

0

我個人使用一個自定義的隨機數發生器,一個自定義加擾器(能夠解讀)和AES加密,輸入字符串,輸出是編碼的二進制密碼一個base64。 (最好的做法雖然是保存哈希密碼數據庫,並進行身份驗證時,哈希提供的密碼和核對數據庫值)

int KeyLength = 16; 
public static Int32 GetASeed(String SeedStr) 
{ 
    Int32 Seed = 0; 
    for (int i = 0; i < SeedStr.Length; i++) 
    { 
     Seed ^= SeedStr[i]; 
    } 
    return Seed; 
} 

public static byte[] Keygen(String Str) 
{ 
    Int32 Seed = GetASeed(Str); 
    Random NumGenerator = new Random(Seed); 
    byte[] Key = new byte[KeyLength]; 
    for (int i = 0; i < KeyLength; i++) 
    { 
     Key[i] = (byte)NumGenerator.Next(256); 
    } 
    return Key; 
} 

public static byte[] Encrypt(String Text, String Key) 
{ 
    Aes Encryptor = Aes.Create(); 
    byte[] Data; 
    Encryptor.Key = Keygen(Key); 
    Encryptor.IV = Keygen(Key + "dec"); 
    Data = Encryptor.CreateEncryptor().TransformFinalBlock(Encoding.UTF8.GetBytes(Text), 0, Text.Length); 
    return Convert.ToBase64String(Data); 
} 


public static String Decrypt(byte[] Data, String KeyPass) 
{ 
    Aes Decryptor = Aes.Create(); 
    Decryptor.Key = Keygen(KeyPass); 
    Decryptor.IV = Keygen(KeyPass + "dec"); 
    Data = Decryptor.CreateDecryptor().TransformFinalBlock(Data, 0, Data.Length); 
    return Encoding.UTF8.GetString(Convert.FromBase64String(Data)); 
} 

用法:

Encrypt(SomePasswordField.Text, "MyWayCoolEnkryptionKeyString"); 
Decrypt(DatabaseUser.Password, "MyWayCoolEnkryptionKeyString"); 

這只是一個骨架的AES加密。