using System; using System.Collections.Generic; using System.IO; using System.Security.Cryptography; using System.Text; namespace CZFW.Core.Security { public class DesEncrypt { private const string DesKey = "CZCMS_desencrypt_2016"; #region ========加密======== /// /// 加密 /// /// /// public static string Encrypt(string text) { return Encrypt(text, DesKey); } /// /// 加密数据 /// /// /// /// public static string Encrypt(string text, string sKey) { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); var inputByteArray = Encoding.Default.GetBytes(text); des.Key = Encoding.ASCII.GetBytes(GetMd5Hash(DesKey).Substring(0, 8)); des.IV = Encoding.ASCII.GetBytes(GetMd5Hash(DesKey).Substring(0, 8)); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); StringBuilder ret = new StringBuilder(); foreach (byte b in ms.ToArray()) { ret.AppendFormat("{0:X2}", b); } return ret.ToString(); } #endregion #region ========解密======== /// /// 解密 /// /// /// public static string Decrypt(string text) { return !string.IsNullOrEmpty(text) ? Decrypt(text, DesKey) : ""; } /// /// 解密数据 /// /// /// /// public static string Decrypt(string text, string sKey) { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); var len = text.Length / 2; byte[] inputByteArray = new byte[len]; int x; for (x = 0; x < len; x++) { var i = Convert.ToInt32(text.Substring(x * 2, 2), 16); inputByteArray[x] = (byte)i; } des.Key = Encoding.ASCII.GetBytes(GetMd5Hash(DesKey).Substring(0, 8)); des.IV = Encoding.ASCII.GetBytes(GetMd5Hash(DesKey).Substring(0, 8)); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); return Encoding.Default.GetString(ms.ToArray()); } public static string GetMd5Hash(string input) { MD5 md5Hash = MD5.Create(); // Convert the input string to a byte array and compute the hash. byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input)); // Create a new Stringbuilder to collect the bytes // and create a string. StringBuilder sBuilder = new StringBuilder(); // Loop through each byte of the hashed data // and format each one as a hexadecimal string. for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("X2")); } // Return the hexadecimal string. return sBuilder.ToString(); } #endregion } }