字串是經常使用的類型,怎樣儲存字串才能最安全呢?答案就是加密。
可以利用C# 中 CryptoStream 來加密和解密字串。CryptoStream方法如下:
程式運行結果如下:
主視窗響應代碼如下:
private void btn_Encrypt_Click(object sender, EventArgs e) { if (txt_password.Text.Length == 4)//判斷加密金鑰長度是否正確 { try { txt_EncryptStr.Text = //調用執行個體ToEncrypt方法得到加密後的字串 new Encrypt().ToEncrypt( txt_password.Text, txt_str.Text); //Encrypt P_Encrypt = new Encrypt(); //P_Encrypt.ToEncrypt("" } catch (Exception ex)//捕獲異常 { MessageBox.Show(ex.Message);//輸出異常資訊 } } else { MessageBox.Show("密鑰長度不符!", "提示");//提示使用者輸入密鑰長度不正確 } } private void btn_UnEncrypt_Click(object sender, EventArgs e) { if (txt_password2.Text.Length == 4)//判斷加密金鑰長度是否正確 { try { txt_str2.Text = //調用ToDecrypt方法得到解密後的字串 new Encrypt().ToDecrypt( txt_password2.Text, txt_EncryptStr2.Text); } catch (Exception ex)//捕獲異常 { MessageBox.Show(ex.Message);//輸出異常資訊 } } else { MessageBox.Show("密鑰長度不符!", "提示");//提示使用者輸入密鑰長度不正確 } }
自訂類代碼如下:
public class Encrypt { internal string ToEncrypt(string encryptKey, string str) { try { byte[] P_byte_key = //將密鑰字串轉換為位元組序列 Encoding.Unicode.GetBytes(encryptKey); byte[] P_byte_data = //將字串轉換為位元組序列 Encoding.Unicode.GetBytes(str); MemoryStream P_Stream_MS = //建立記憶體流對象 new MemoryStream(); CryptoStream P_CryptStream_Stream = //建立加密流對象 new CryptoStream(P_Stream_MS,new DESCryptoServiceProvider(). CreateEncryptor(P_byte_key, P_byte_key),CryptoStreamMode.Write); P_CryptStream_Stream.Write(//向加密流中寫入位元組序列 P_byte_data, 0, P_byte_data.Length); P_CryptStream_Stream.FlushFinalBlock();//將資料壓入基礎流 byte[] P_bt_temp =//從記憶體流中擷取位元組序列 P_Stream_MS.ToArray(); P_CryptStream_Stream.Close();//關閉加密流 P_Stream_MS.Close();//關閉記憶體流 return //方法返回加密後的字串 Convert.ToBase64String(P_bt_temp); } catch (CryptographicException ce) { throw new Exception(ce.Message); } } internal string ToDecrypt(string encryptKey, string str) { try { byte[] P_byte_key = //將密鑰字串轉換為位元組序列 Encoding.Unicode.GetBytes(encryptKey); byte[] P_byte_data = //將加密後的字串轉換為位元組序列 Convert.FromBase64String(str); MemoryStream P_Stream_MS =//建立記憶體流對象並寫入資料 new MemoryStream(P_byte_data); CryptoStream P_CryptStream_Stream = //建立加密流對象 new CryptoStream(P_Stream_MS,new DESCryptoServiceProvider(). CreateDecryptor(P_byte_key, P_byte_key),CryptoStreamMode.Read); byte[] P_bt_temp = new byte[200];//建立位元組序列對象 MemoryStream P_MemoryStream_temp =//建立記憶體流對象 new MemoryStream(); int i = 0;//建立記數器 while ((i = P_CryptStream_Stream.Read(//使用while迴圈得到解密資料 P_bt_temp, 0, P_bt_temp.Length)) > 0) { P_MemoryStream_temp.Write(//將解密後的資料放入記憶體流 P_bt_temp, 0, i); } return //方法返回解密後的字串 Encoding.Unicode.GetString(P_MemoryStream_temp.ToArray()); } catch (CryptographicException ce) { throw new Exception(ce.Message); } } }
代碼:下載