/// <summary> /// DES 加解密 /// </summary> public class DES { /// <summary> /// DES加密,对接其他语言使用同一规则用 /// </summary> /// <param name="pToEncrypt"></param> /// <param name="key"></param> /// <param name="IV"></param> /// <returns></returns> public static string EncryptString(string pToEncrypt, string key, string IV) { Byte[] keyArray = new byte[32]; keyArray = System.Text.UTF8Encoding.UTF8.GetBytes(key); Byte[] ivArray = new byte[32]; ivArray = System.Text.UTF8Encoding.UTF8.GetBytes(IV); Byte[] toEncryptArray = System.Text.UTF8Encoding.UTF8.GetBytes(pToEncrypt); System.Security.Cryptography.RijndaelManaged rDel = new System.Security.Cryptography.RijndaelManaged(); rDel.Key = keyArray; rDel.IV = ivArray; rDel.Mode = System.Security.Cryptography.CipherMode.CBC; rDel.Padding = System.Security.Cryptography.PaddingMode.PKCS7; System.Security.Cryptography.ICryptoTransform cTransform = rDel.CreateEncryptor(); Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return Convert.ToBase64String(resultArray, 0, resultArray.Length); } /// <summary> /// DES加密 /// </summary> /// <param name="input">待加密的字符串</param> /// <param name="key">加密密钥</param> /// <returns></returns> public static string Encrypt(string EncryptString, byte[] Key, byte[] IV) { //byte[] rgbKey = Encoding.UTF8.GetBytes(key.Substring(0, 8)); byte[] inputByteArray = Encoding.UTF8.GetBytes(EncryptString); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); MemoryStream mStream = new MemoryStream(); CryptoStream cStream = new CryptoStream(mStream, des.CreateEncryptor(Key, IV), CryptoStreamMode.Write); cStream.Write(inputByteArray, 0, inputByteArray.Length); cStream.FlushFinalBlock(); return Convert.ToBase64String(mStream.ToArray()); } /// <summary> /// DES解密 /// </summary> /// <param name="input">待解密的字符串</param> /// <param name="key">解密密钥,要求为8位,和加密密钥相同</param> /// <returns>解密成功返回解密后的字符串,失败返源串</returns> public static string Decrypt(string DecryptString, byte[] Key, byte[] IV) { try { //byte[] rgbKey = Encoding.UTF8.GetBytes(Key); byte[] inputByteArray = Convert.FromBase64String(DecryptString); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); MemoryStream mStream = new MemoryStream(); CryptoStream cStream = new CryptoStream(mStream, des.CreateDecryptor(Key, IV), CryptoStreamMode.Write); cStream.Write(inputByteArray, 0, inputByteArray.Length); cStream.FlushFinalBlock(); return Encoding.UTF8.GetString(mStream.ToArray()); } catch { return ""; } } }