本文實例講述了C#字符串加密解密方法。分享給大家供大家參考。具體如下:
#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#程序設計有所幫助。
新聞熱點
疑難解答