public class DESDemo { /// <summary> /// DES加密方法 /// </summary> /// <param name="text">明文</param> /// <param name="sKey">密钥</param> /// <param name="iv">向量</param> /// <returns>加密后的密文</returns> public static string DESEncrypt(string text, string sKey,string iv) { using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { byte[] byteArray; byteArray = Encoding.Default.GetBytes(text); des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication. HashPasswordForStoringInConfigFile(sKey, "MD5").Substring(0, 8)); des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication. HashPasswordForStoringInConfigFile(iv, "MD5").Substring(0, 8)); using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(byteArray, 0, byteArray.Length); cs.FlushFinalBlock(); //StringBuilder ret = new StringBuilder(); //foreach (byte b in ms.ToArray()) //{ // ret.AppendFormat("{0:X2}", b); //} return Convert.ToBase64String(ms.ToArray()); } } } } /// <summary> /// DES解密方法 /// </summary> /// <param name="text">密文</param> /// <param name="sKey">密钥</param> /// <param name="iv">向量</param> /// <returns>解密后的明文</returns> public static string DESDecrypt(string text, string sKey,string iv) { using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { //int len; //len = text.Length / 2; //byte[] byteArray = new byte[len]; //int x, i; //for (x = 0; x < len; x++) //{ // i = Convert.ToInt32(text.Substring(x * 2, 2), 16); // byteArray[x] = (byte)i; //} byte[] byteArray; byteArray = Convert.FromBase64String(text); try { des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication. HashPasswordForStoringInConfigFile(sKey, "MD5").Substring(0, 8)); des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication. HashPasswordForStoringInConfigFile(iv, "MD5").Substring(0, 8)); using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(byteArray, 0, byteArray.Length); cs.FlushFinalBlock(); string estring = Encoding.Default.GetString(ms.ToArray()); return estring; } } } catch (Exception ex) { throw ex; } } } }
static void Main(string[] args) { var text = DESDemo.DESEncrypt("你我他", "key", "key"); DESDemo.DESDecrypt(text, "key","key"); Console.WriteLine("加密后:"+text); Console.WriteLine("解密后:"+DESDemo.DESDecrypt(text, "key", "key")); Console.ReadKey(); }
运行结果: