//名称空间 using System; using System.Security.Cryptography; using System.IO; using System.Text; /**/ /// <summary> /// DES算法描述简介: /// DES是Data Encryption Standard(数据加密标准)的缩写。它是由IBM公司研制的一种加密算法, /// 美国国家标准局于1977年公布把它作为非机要部门使用的数据加密标准; /// 它是一个分组加密算法,他以64位为分组对数据加密。 /// 同时DES也是一个对称算法:加密和解密用的是同一个算法。 /// 它的密匙长度是56位(因为每个第8 位都用作奇偶校验), /// 密匙可以是任意的56位的数,而且可以任意时候改变. /// </summary> //默认密钥向量 private static byte[] Keys ={ 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; /// <summary> /// DES加密字符串 /// </summary> /// <param name="encryptString">待加密的字符串</param> /// <param name="encryptKey">加密密钥,要求为8位</param> /// <returns>加密成功返回加密后的字符串,失败返回源串</returns> public static string EncryptDES(string encryptString, string encryptKey) { try { byte[] Key = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8)); byte[] IV = Keys; byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString); DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider(); MemoryStream mStream = new MemoryStream(); CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(Key, IV), CryptoStreamMode.Write); cStream.Write(inputByteArray, 0, inputByteArray.Length); cStream.FlushFinalBlock(); return Convert.ToBase64String(mStream.ToArray()); } catch { return encryptString; } } /// <summary> /// DES解密字符串 /// </summary> /// <param name="decryptString">待解密的字符串</param> /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param> /// <returns>解密成功返回解密后的字符串,失败返源串</returns> public static string DescryptDES(string descryptString, string descryptKey) { try { byte[] Key = Encoding.UTF8.GetBytes(descryptKey.Substring(0,8)); byte[] IV = Keys; byte[] inputByteArray = Convert.FromBase64String(descryptString); DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider(); MemoryStream mStream = new MemoryStream(); CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(Key, IV), CryptoStreamMode.Write); cStream.Write(inputByteArray, 0, inputByteArray.Length); cStream.FlushFinalBlock(); return Encoding.UTF8.GetString(mStream.ToArray()); } catch { return descryptString; } }
实例
protected void Page_Load(object sender, EventArgs e) { Response.Write("加密字符:hello world!,密钥为:hongkaihua@126.com"); string str = EncryptDES("hello world!","hongkaihua@126.com"); Response.Write("DES加密:" + str); Response.Write("DES解密:" + DescryptDES(str, "hongkaihua@126.com")); }