1.引用:
using System.Security.Cryptography;
using System.Text;
2.代碼
static string encryptKey = "abcd";//字符串加密密鑰(注意:密鑰只能是4位)
public string Encrypt(string str)
{//加密字符串
try
{
byte[] key = Encoding.Unicode.GetBytes(encryptKey);//密鑰
byte[] data = Encoding.Unicode.GetBytes(str);//待加密字符串
DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();//加密、解密對象
MemoryStream MStream = new MemoryStream();//內存流對象
//用內存流實例化加密流對象
CryptoStream CStream = new CryptoStream(MStream, descsp.CreateEncryptor(key, key), CryptoStreamMode.Write);
CStream.Write(data, 0, data.Length);//向加密流中寫入數據
CStream.FlushFinalBlock();//將數據壓入基礎流
byte[] temp = MStream.ToArray();//從內存流中獲取字節序列
CStream.Close();//關閉加密流
MStream.Close();//關閉內存流
return Convert.ToBase64String(temp);//返回加密后的字符串
}
catch
{
return str;
}
}
public string Decrypt(string str)
{//解密字符串
try
{
byte[] key = Encoding.Unicode.GetBytes(encryptKey);//密鑰
byte[] data = Convert.FromBase64String(str);//待解密字符串
DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();//加密、解密對象
MemoryStream MStream = new MemoryStream();//內存流對象
//用內存流實例化解密流對象
CryptoStream CStream = new CryptoStream(MStream, descsp.CreateDecryptor(key, key), CryptoStreamMode.Write);
CStream.Write(data, 0, data.Length);//向加密流中寫入數據
CStream.FlushFinalBlock();//將數據壓入基礎流
byte[] temp = MStream.ToArray();//從內存流中獲取字節序列
CStream.Close();//關閉加密流
MStream.Close();//關閉內存流
return Encoding.Unicode.GetString(temp);//返回解密后的字符串
}
catch
{
return str;
}
}
參考:https://www.cnblogs.com/nb08611033/p/9183198.html