使用 DESCryptoServiceProvider 進行加密,輸出 Base64 字串:
textBox1.ReadOnly = false;
try
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] key = Encoding.Unicode.GetBytes(encryptKey); // 金鑰需 8 位元組
byte[] data = Encoding.Unicode.GetBytes(textBox1.Text.Trim());
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, key), CryptoStreamMode.Write);
cs.Write(data, 0, data.Length);
cs.FlushFinalBlock();
textBox2.Text = Convert.ToBase64String(ms.ToArray());
textBox3.Text = "";
textBox3.ReadOnly = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "資訊", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
textBox3.ReadOnly = false;
try
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] key = Encoding.Unicode.GetBytes(encryptKey);
byte[] data = Convert.FromBase64String(textBox2.Text.Trim());
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, key), CryptoStreamMode.Write);
cs.Write(data, 0, data.Length);
cs.FlushFinalBlock();
textBox3.Text = Encoding.Unicode.GetString(ms.ToArray());
textBox1.Text = "";
textBox1.ReadOnly = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "資訊", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
| 關鍵字 | 說明 |
|---|---|
0 | 數值型別未指派時的預設值。 |
空字串 "" | 字串型別未指派時的預設值。 |
null | 表示變數不參考任何物件,為明確指派或運算結果。 |
String.Empty | 等同 "",語意更明確,效能略優。 |
Nothing (VB.NET) | C# 對應 default(T),用於將參考型別變數與實體物件分離。 |
常用操作如首字大寫、字串比較、子串插入等較簡單,此處略過。