https://github.com/ted59438/EnglishVocabulary_MySQL
新增一組學生的帳號密碼,密碼以非明文的方式存到資料庫
private void insertStudentBtn_Click(object sender, EventArgs e)
{
string sql;
Dictionary<string, object> parameters;
sql = @"SELECT COUNT(StudentID)
FROM Student
WHERE Username = @Username";
parameters = new Dictionary<string, object>()
{
{"Username", studentUsernameTextBox.Text }
};
try
{
if (queryScalar(sql, parameters) != 0)
{
MessageBox.Show("學生帳號已經存在!", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
sql = @"INSERT
INTO Student(StudentID, RealName, Birthdate, Username, Password)
VALUES (@StudentID, @RealName, @Birthdate, @Username, SHA2(@Password, 256))";
parameters = new Dictionary<string, object>()
{
{"StudentID", Guid.NewGuid().ToString() },
{"RealName", studentNameTextBox.Text },
{"Birthdate", studentBirthdatePicker.Value },
{"Username", studentUsernameTextBox.Text },
{"Password", studentPasswordTextBox.Text }
};
try
{
queryNoneReturn(sql, parameters);
queryStudentBtn.PerformClick();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// 交易查詢:新修刪
/// </summary>
/// <param name="sql"></param>
/// <param name="parameters"></param>
private void queryNoneReturn(string sql, Dictionary<string, object> parameters)
{
MySqlCommand command = getAndBindCommand(sql, parameters);
try
{
// 1. 開啟連線
command.Connection.Open();
// 2. 開啟Transcation
command.Transaction = command.Connection.BeginTransaction();
// 3. 執行查詢
command.ExecuteNonQuery();
// 4.1 執行成功,送出Commit,確認執行查詢後結果
command.Transaction.Commit();
command.Connection.Close();
}
catch (Exception)
{
// 4.2 執行失敗,送出Rollback,返回執行查詢前的結果
command.Transaction.Rollback();
command.Connection.Close();
throw;
}
}
經過雜湊演算法(Hashing algorithms)計算出來的資料指紋(data fingerprint),用來識別檔案與資料是否有被竄改,以保證檔案與資料確實是由原創者所提供。
將可輕易辨識的明文資訊,修改成不可讀的密文資訊。只有擁有解密方法的對象,經由解密過程,才能將密文還原為正常可讀的內容。
所以如果看到一個網站能讓你查詢密碼,代表哪一天網站的資料庫被踢的時候
你的密碼也會被別人看光光。
常見的雜湊函式:
MySQL:
https://dev.mysql.com/doc/refman/5.6/en/encryption-functions.html
https://mariadb.com/kb/en/library/encryption-hashing-and-compression-functions/
延伸閱讀:
https://openhome.cc/Gossip/EJB3Gossip/TransactionABC.html
/// <summary>
/// 交易查詢:新修刪
/// </summary>
/// <param name="sql"></param>
/// <param name="parameters"></param>
private void queryNoneReturn(string sql, Dictionary<string, object> parameters)
{
MySqlCommand command = getAndBindCommand(sql, parameters);
try
{
// 1. 開啟連線
command.Connection.Open();
// 2. 開啟Transcation
command.Transaction = command.Connection.BeginTransaction();
// 3. 執行查詢
command.ExecuteNonQuery();
// 4.1 執行成功,送出Commit,確認執行查詢後結果
command.Transaction.Commit();
command.Connection.Close();
}
catch (Exception)
{
// 4.2 執行失敗,送出Rollback,返回執行查詢前的結果
command.Transaction.Rollback();
command.Connection.Close();
throw;
}
}