1.导入两个名称空间:
using System.Security.Cryptography;
using System.Text.RegularExpressions;
2. 加密解密类:
private static readonly string sKey="qJzGEh6hESZDVJeCnFPGuxzaiB7NLQM3";//密钥
private static readonly string sIV="qcDY6X+aPLw=";//矢量,矢量可以为空
private static SymmetricAlgorithm mCSP=new TripleDESCryptoServiceProvider();//构造一个对称算法
3.加密方法:
public static string EncryptDes(string source)
{
ICryptoTransform ct;
MemoryStream ms;
CryptoStream cs;
byte[] byt;
string str=null;
mCSP.Key=Convert.FromBase64String(sKey);
mCSP.IV=Convert.FromBase64String(sIV);
mCSP.Mode=System.Security.Cryptography.CipherMode.ECB;
mCSP.Padding=System.Security.Cryptography.PaddingMode.PKCS7;
ct = mCSP.CreateEncryptor(mCSP.Key, mCSP.IV);
byt = Encoding.UTF8.GetBytes(source);
ms = new MemoryStream();
cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
cs.Write(byt, 0, byt.Length);
cs.FlushFinalBlock();
cs.Close();
str=Convert.ToBase64String(ms.ToArray());
return str;
}
4.机密方法:
public static string DecryptDes(string source)
{
ICryptoTransform ct;
MemoryStream ms;
CryptoStream cs;
byte[] byt;
string str=null;
mCSP.Key=Convert.FromBase64String(sKey);
mCSP.IV=Convert.FromBase64String(sIV);
mCSP.Mode=System.Security.Cryptography.CipherMode.ECB;
mCSP.Padding=System.Security.Cryptography.PaddingMode.PKCS7;
ct = mCSP.CreateDecryptor(mCSP.Key, mCSP.IV);
byt = Convert.FromBase64String(source);
ms = new MemoryStream();
cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
cs.Write(byt, 0, byt.Length);
cs.FlushFinalBlock();
cs.Close();
str= Encoding.UTF8.GetString(ms.ToArray());
return str;
}