加密解密

Posted on 2019-11-21 11:32  桀骜不逊  阅读(284)  评论(0编辑  收藏  举报

 

//加密

public static string GDEncode(string data, string Key) 
{
Key = "12345678";
byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(Key);
byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(Key);
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 GJDecode(string data, string Key) 
{
Key = "12345678";
byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(Key);
byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(Key);
byte[] byEnc;
try
{
byEnc = Convert.FromBase64String(data);
}
catch
{
return data;
}
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);
String str;
str = sr.ReadToEnd();
if (str.Trim() == "") str = data;
return str;
}