日期:2014-05-19 浏览次数:20657 次
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Security.Cryptography; namespace WindowsFormsApplication1 { /// <summary> /// 加密解密操作类 /// </summary> public class EDHelper { private static SymmetricAlgorithm mCSP = new DESCryptoServiceProvider(); private static string vectorKey = "T/Zl4XkLe8I=";//"cEbmGVzevBs="; private static string ivKey = "5vikZLWsu7g=";//"EHCtpIFk84I="; /// <summary> /// 对一个字符串进行加密 /// </summary> /// <param name="str">需要加密的字符串</param> /// <returns>返回一个后的字符串</returns> public static string Encrypt(string str) { if (string.IsNullOrEmpty(str)) return ""; try { byte[] bytes; string strResult = string.Empty; ICryptoTransform ct = mCSP.CreateEncryptor(Convert.FromBase64String(vectorKey), Convert.FromBase64String(ivKey)); bytes = Encoding.UTF8.GetBytes(str); using (MemoryStream ms = new MemoryStream()) { CryptoStream cs = new CryptoStream(ms, ct, CryptoStreamMode.Write); cs.Write(bytes, 0, bytes.Length); cs.FlushFinalBlock(); cs.Close(); strResult = Convert.ToBase64String(ms.ToArray()); } return strResult; } catch { return ""; } } /// <summary> /// 对加密的字符串进行解密 /// </summary> /// <param name="str">需要解密的内容</param> /// <returns>解密后的字符串</returns> public static string Decrypt(string str) { if (string.IsNullOrEmpty(str)) return ""; try { byte[] bytes; string strResult = string.Empty; ICryptoTransform ct = mCSP.CreateDecryptor(Convert.FromBase64String(vectorKey), Convert.FromBase64String(ivKey)); bytes = Convert.FromBase64String(str); using (MemoryStream ms = new MemoryStream()) { CryptoStream cs = new CryptoStream(ms, ct, CryptoStreamMode.Write); cs.Write(bytes, 0, bytes.Length); cs.FlushFinalBlock(); cs.Close(); strResult = Encoding.UTF8.GetString(ms.ToArray()); } return strResult; } catch { return ""; } } /// <summary> /// 根据字符串获取MD5哈希值 /// </summary> /// <param name="str">目标字符串</param> /// <returns>返回MD5哈希值</returns> public static int GetMD5Hash(string str) { MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] hash = md5.ComputeHash(System.Text.Encoding.Unicode.GetBytes(str)); Int32 hashInt = System.BitConverter.ToInt32(hash, 0); return hashInt; } } }