首先要引用
using System.Security.Cryptography;
然后是这两个方法
//加密
public static string Encode(string data)
{
string KEY_64 = "VavicApp";
string IV_64 = "VavicApp";
byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);
DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
int i = cryptoProvider.KeySize;
MemoryStream ms = new MemoryStream();
CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);
StreamWriter sw = new StreamWriter(cst);
sw.Write(data);
sw.Flush();
cst.FlushFinalBlock();
sw.Flush();
return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
}
//解密
public static string Decode(string data)
{
string KEY_64 = "VavicApp";
string IV_64 = "VavicApp";
byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);
byte[] byEnc;
try
{
byEnc = Convert.FromBase64String(data);
}
catch
{
return null;
}
DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream(byEnc);
CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
StreamReader sr = new StreamReader(cst);
return sr.ReadToEnd();
}
在使用时
在aspx.cs页面中引用using System.Security.Cryptography;
using System.IO;
在某方法是调用举例
string pinb = this.tbx_Epin.Text.ToString();//获取要加密的字符串
string PIN = Code.Encode(pinb).ToString();//进行加密
解密的时候相反.
..........//先获取加密过的字符串
string pin= Code.Decode(pin).ToString();//解密