實驗目的:
進一步完善系統
敏感數據加密,採用密文存儲。例如密碼需要加密存儲。
實驗內容:
目標效果:
註冊窗體:
登錄窗體:
主窗體:
實驗步驟:
1、數據庫數據準備:
首先需要在數據庫裏準備實驗需要用到的數據
2、建立新項目:
3、新建窗體:
4、根據目標效果從工具箱添加組件:
5、編寫代碼:
1.登錄窗體:
注意點:
1.1和數據庫一樣,使用之前必須要進行引入,快捷鍵[Alt]+[Enter],或者是自己手動引入也可以。
1.2
生成驗證碼的代碼裏,應該要對對應的label進行綁定
2.註冊窗體:
注意點:
1.需要對User ID的textBox設置leave事件,意思是離開焦點就觸發的事件
3.主窗體:
注意點:
1.由正常的使用經驗得知,在主窗體進行關閉的時候,程序也應該停止運行,所以我們需要添加一個窗體的關閉事件(FormClosed)。方法和註冊窗體的textBox1的leave事件是一樣的。
運行效果:
註冊窗體:
上傳圖片
輸入用戶名不規範時:
註冊成功
登錄窗體:
現在使用註冊過的賬戶密碼來進行登錄:
除了在賬號、密碼、驗證碼都正確的情況下成功登錄,其他情況下都是登錄錯誤。
登錄成功:
主窗體:
點擊refresh對登錄日誌進行刷新
輸入USerID再點擊Show Photo出現圖像
代碼:
Login.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Test518
{
public partial class Login : Form
{
public Login()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string username = textBox1.Text.Trim(); //取出賬號
string password = EncryptWithMD5(textBox2.Text.Trim()); //取出密碼並加密
if (username == "admin")
password = "123";//測試用例,便於初始化時候的 admin 密碼 123可以順利登陸。程序完成後可註釋掉這行代碼。
//string connstr = ConfigurationManager.ConnectionStrings["connectionString"].ToString(); //讀取連接字符串
string myConnString = "Data Source=.;Initial Catalog=curricula_variable_system;Persist Security Info=True;User ID=sa;Password=******";
SqlConnection sqlConnection = new SqlConnection(myConnString); //實例化連接對象
sqlConnection.Open();
string sql = "select UserID,UserPassword from SysUser where UserID = '" + username + "' and UserPassword = '" + password + "'"; //編寫SQL命令
SqlCommand sqlCommand = new SqlCommand(sql, sqlConnection);
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
if (sqlDataReader.HasRows && textBox3.Text == code)
{
MessageBox.Show("歡迎使用!"); //登錄成功
Main form2 = new Main();
form2.Show();
this.Hide();
}
else
{
MessageBox.Show("登錄失敗!");
return;
}
sqlDataReader.Close();
sql = "insert into SysLog values ( '" + username + "' , '" + DateTime.Now + "' , '" + "Login" + "')"; //編寫SQL命令
sqlCommand = new SqlCommand(sql, sqlConnection);
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
}
public static string EncryptWithMD5(string source)
{
byte[] sor = Encoding.UTF8.GetBytes(source);
MD5 md5 = MD5.Create();
byte[] result = md5.ComputeHash(sor);
StringBuilder strbul = new StringBuilder(40);
for (int i = 0; i < result.Length; i++)
{
strbul.Append(result[i].ToString("x2"));//加密結果"x2"結果爲32位,"x3"結果爲48位,"x4"結果爲64位
}
return strbul.ToString();
}
public string code;
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Register register = new Register();
register.ShowDialog();
}
private void Login_Load(object sender, EventArgs e)
{
//隨機實例化
Random ran = new Random();
int number;
char code1;
//取五個數
for (int i = 0; i < 5; i++)
{
number = ran.Next();
if (number % 2 == 0)
code1 = (char)('0' + (char)(number % 10));
else
code1 = (char)('A' + (char)(number % 26)); //轉化爲字符
this.code += code1.ToString();
}
label5.Text = code;
}
private void label5_Click(object sender, EventArgs e)
{
}
}
}
Register.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Test518
{
public partial class Register : Form
{
public Register()
{
InitializeComponent();
}
private void Register_Load(object sender, EventArgs e)
{
}
public Byte[] mybyte = new byte[0];
public static string EncryptWithMD5(string source)
{
byte[] sor = Encoding.UTF8.GetBytes(source);
MD5 md5 = MD5.Create();
byte[] result = md5.ComputeHash(sor);
StringBuilder strbul = new StringBuilder(40);
for (int i = 0; i < result.Length; i++)
{
strbul.Append(result[i].ToString("x2"));//加密結果"x2"結果爲32位,"x3"結果爲48位,"x4"結果爲64位
}
return strbul.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
string connString = "Data Source=.;Initial Catalog=curricula_variable_system;Persist Security Info=True;User ID=sa;Password=********";//數據庫連接字符串
SqlConnection connection = new SqlConnection(connString);//創建connection對象
string sql = "insert into SysUser (UserID, UserPassWord , UserSchoolID, UserMobile, UserBirthday , UserIdentity , UserPhoto ) " +
"values (@userid, @userpassword,@userschoolid,@usermobile,@userbirthday,@useridentity,@userphoto)";
SqlCommand command = new SqlCommand(sql, connection);
SqlParameter sqlParameter = new SqlParameter("@userid", textBox1.Text);
command.Parameters.Add(sqlParameter);
sqlParameter = new SqlParameter("@userpassword", EncryptWithMD5(textBox2.Text));
command.Parameters.Add(sqlParameter);
sqlParameter = new SqlParameter("@userschoolid", textBox3.Text);
command.Parameters.Add(sqlParameter);
sqlParameter = new SqlParameter("@usermobile", textBox4.Text);
command.Parameters.Add(sqlParameter);
sqlParameter = new SqlParameter("@userbirthday", dateTimePicker1.Value);
command.Parameters.Add(sqlParameter);
sqlParameter = new SqlParameter("@useridentity", comboBox1.Text);
command.Parameters.Add(sqlParameter);
sqlParameter = new SqlParameter("@userphoto", SqlDbType.VarBinary, mybyte.Length, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, mybyte);
command.Parameters.Add(sqlParameter);
//打開數據庫連接
connection.Open();
command.ExecuteNonQuery();
connection.Close();
MessageBox.Show("register succeed");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void button3_Click(object sender, EventArgs e)
{
//打開瀏覽圖片對話框
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.ShowDialog();
string picturePath = openFileDialog.FileName;//獲取圖片路徑
//文件的名稱,每次必須更換圖片的名稱,這裏很爲不便
//創建FileStream對象
FileStream fs = new FileStream(picturePath, FileMode.Open, FileAccess.Read);
//聲明Byte數組
mybyte = new byte[fs.Length];
//讀取數據
fs.Read(mybyte, 0, mybyte.Length);
pictureBox1.Image = Image.FromStream(fs);
fs.Close();
}
private void textBox1_Leave(object sender, EventArgs e)
{
if (textBox1.Text.Trim() != "")
{
//使用regex(正則表達式)進行格式設置 至少有數字、大寫字母、小寫字母各一個。最少3個字符、最長20個字符。
Regex regex = new Regex(@"(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{3,20}");
if (regex.IsMatch(textBox1.Text))//判斷格式是否符合要求
{
//MessageBox.Show("輸入密碼格式正確!");
}
else
{
MessageBox.Show("至少有數字、大寫字母、小寫字母各一個。最少3個字符、最長20個字符!");
textBox1.Focus();
}
}
else
{
MessageBox.Show("Please fill in the full information!");
}
}
}
}
Main.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Test518
{
public partial class Main : Form
{
public Main()
{
InitializeComponent();
}
private void button3_Click(object sender, EventArgs e)
{
this.sysLogTableAdapter.Fill(this.curricula_variable_systemDataSet.SysLog);
}
private void button1_Click(object sender, EventArgs e)
{
try
{
string connString = "Data Source=.;Initial Catalog=curricula_variable_system;Persist Security Info=True;User ID=sa;Password=*******";//數據庫連接字符串
SqlConnection connection = new SqlConnection(connString);//創建connection對象
//打開數據庫連接
connection.Open();
//創建SQL語句
string sql = "select UserPhoto from SysUser where UserID = '" + textBox1.Text + "'";
//創建SqlCommand對象
SqlCommand command = new SqlCommand(sql, connection);
//創建DataAdapter對象
SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
//創建DataSet對象
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet, "SysUser");
int c = dataSet.Tables["SysUser"].Rows.Count;
if (c > 0)
{
Byte[] mybyte = new byte[0];
mybyte = (Byte[])(dataSet.Tables["SysUser"].Rows[c - 1]["UserPhoto"]);
MemoryStream ms = new MemoryStream(mybyte);
pictureBox1.Image = Image.FromStream(ms);
}
else
pictureBox1.Image = null;
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void Main_FormClosed(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
private void Main_Load(object sender, EventArgs e)
{
// TODO: 這行代碼將數據加載到表“curricula_variable_systemDataSet.SC”中。您可以根據需要移動或刪除它。
this.sCTableAdapter.Fill(this.curricula_variable_systemDataSet.SC);
// TODO: 這行代碼將數據加載到表“curricula_variable_systemDataSet.Course”中。您可以根據需要移動或刪除它。
this.courseTableAdapter.Fill(this.curricula_variable_systemDataSet.Course);
// TODO: 這行代碼將數據加載到表“curricula_variable_systemDataSet.Student”中。您可以根據需要移動或刪除它。
this.studentTableAdapter.Fill(this.curricula_variable_systemDataSet.Student);
// TODO: 這行代碼將數據加載到表“curricula_variable_systemDataSet.SysLog”中。您可以根據需要移動或刪除它。
this.sysLogTableAdapter.Fill(this.curricula_variable_systemDataSet.SysLog);
// TODO: 這行代碼將數據加載到表“curricula_variable_systemDataSet.SysUser”中。您可以根據需要移動或刪除它。
this.sysUserTableAdapter.Fill(this.curricula_variable_systemDataSet.SysUser);
}
}
}