C#字符串加密解密辦法實例。本站提示廣大學習愛好者:(C#字符串加密解密辦法實例)文章只能為提供參考,不一定能成為您想要的結果。以下是C#字符串加密解密辦法實例正文
本文實例講述了C#字符串加密解密辦法。分享給年夜家供年夜家參考。詳細以下:
#region 加密解密
static string encryptKey= "Oyea";
#region 加密字符串 public static string Encrypt(string str)
/// <summary>
/// 加密字符串
/// </summary>
/// <param name="str">要加密的字符串</param>
/// <returns>前往加密後的字符串</returns>
public static string Encrypt(string str)
{
DESCryptoServiceProvider descsp = new DESCryptoServiceProvider(); //實例化加/解密類對象
byte[] key = Encoding.Unicode.GetBytes(encryptKey); //界說字節數組,用來存儲密鑰
byte[] data = Encoding.Unicode.GetBytes(str);//界說字節數組,用來存儲要加密的字符串
MemoryStream MStream = new MemoryStream();//實例化內存流對象
//應用內存流實例化加密流對象
CryptoStream CStream = new CryptoStream(MStream,descsp.CreateEncryptor(key, key), CryptoStreamMode.Write);
CStream.Write(data,0, data.Length); //向加密流中寫入數據
CStream.FlushFinalBlock(); //釋放加密流
return Convert.ToBase64String(MStream.ToArray());//前往加密後的字符串
}
#endregion
#region 解密字符串 public static string Decrypt(string str)
/// <summary>
/// 解密字符串
/// </summary>
/// <param name="str">要解密的字符串</param>
/// <returns>前往解密後的字符串</returns>
public static string Decrypt(string str)
{
DESCryptoServiceProvider descsp = new DESCryptoServiceProvider(); //實例化加/解密類對象
byte[] key = Encoding.Unicode.GetBytes(encryptKey); //界說字節數組,用來存儲密鑰
byte[] data = Convert.FromBase64String(str);//界說字節數組,用來存儲要解密的字符串
MemoryStream MStream = new MemoryStream();//實例化內存流對象
//應用內存流實例化解密流對象
CryptoStream CStream = new CryptoStream(MStream, descsp.CreateDecryptor(key, key), CryptoStreamMode.Write);
CStream.Write(data,0, data.Length); //向解密流中寫入數據
CStream.FlushFinalBlock(); //釋放解密流
return Encoding.Unicode.GetString(MStream.ToArray()); //前往解密後的字符串
}
#endregion
#endregion
願望本文所述對年夜家的C#法式設計有所贊助。