//很陽春的加解密函式,改寫自http://goo.gl/sos1J
//程式以示意為主,只適用小型字串處理,未包含參數檢核,防錯邏輯
public class MyCipher
{
byte[] rgbKey = new byte[8];
byte[] rgbIv = new byte[8];
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
public MyCipher(string key)
{
var hash = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(key));
Array.Copy(hash, 0, rgbKey, 0, 8);
Array.Copy(hash, 8, rgbIv, 0, 8);
}
public string Encrypt(string rawString)
{
using (var ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms,
des.CreateEncryptor(rgbKey, rgbIv), CryptoStreamMode.Write))
{
byte[] buff = Encoding.UTF8.GetBytes(rawString);
cs.Write(buff, 0, buff.Length);
}
return Convert.ToBase64String(ms.ToArray());
}
}
public string Decrypt(string encString)
{
using (var ms = new MemoryStream(Convert.FromBase64String(encString)))
{
using (var cs = new CryptoStream(ms,
des.CreateDecryptor(rgbKey, rgbIv), CryptoStreamMode.Read))
{
using (var sr = new StreamReader(cs))
{
return sr.ReadToEnd();
}
}
}
}
}