using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; namespace JwKdsV.Core.Utils { public static class DesUtils { //默认密钥向量 private static byte[] Keys = { 1 , 5 , 6 , 3 ,8 , 5 ,9 , 0 }; // 密钥 private static String KEY_STR = "$QBOSSY$"; public static string Encrypt(string data) { try { byte[] rgbKey = Encoding.UTF8.GetBytes(KEY_STR.Substring(0 , 8)); byte[] rgbIV = Keys; byte[] inputByteArray = Encoding.UTF8.GetBytes(data); DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider(); MemoryStream mStream = new MemoryStream(); CryptoStream cStream = new CryptoStream(mStream , dCSP.CreateEncryptor(rgbKey , rgbIV) , CryptoStreamMode.Write); cStream.Write(inputByteArray , 0 , inputByteArray.Length); cStream.FlushFinalBlock(); return SafeBase64Utils.ToBase64(mStream.ToArray()); } catch { return data; } } public static string Decrypt(string data) { try { byte[] rgbKey = Encoding.UTF8.GetBytes(KEY_STR); byte[] rgbIV = Keys; byte[] inputByteArray = Convert.FromBase64String(SafeBase64Utils.SafeBase64ToBase64(data)); DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider(); MemoryStream mStream = new MemoryStream(); CryptoStream cStream = new CryptoStream(mStream , DCSP.CreateDecryptor(rgbKey , rgbIV) , CryptoStreamMode.Write); cStream.Write(inputByteArray , 0 , inputByteArray.Length); cStream.FlushFinalBlock(); return Encoding.UTF8.GetString(mStream.ToArray()); } catch { return data; } } /// ///3DES加密 /// /// 加密数据 /// 24位字符的密钥字符串 /// 8位字符的初始化向量字符串 /// public static string DES3Encrypt(string originalValue, string key, string IV) { SymmetricAlgorithm sa; ICryptoTransform ct; MemoryStream ms; CryptoStream cs; byte[] byt; sa = new TripleDESCryptoServiceProvider(); sa.Key = Encoding.UTF8.GetBytes(key); sa.IV = Encoding.UTF8.GetBytes(IV); ct = sa.CreateEncryptor(); byt = Encoding.UTF8.GetBytes(originalValue); ms = new MemoryStream(); cs = new CryptoStream(ms, ct, CryptoStreamMode.Write); cs.Write(byt, 0, byt.Length); cs.FlushFinalBlock(); cs.Close(); return Convert.ToBase64String(ms.ToArray()); } /// /// 3DES解密 /// /// 解密数据 /// 24位字符的密钥字符串(需要和加密时相同) /// 8位字符的初始化向量字符串(需要和加密时相同) /// public static string DES3Decrypst(string data, string key, string IV) { SymmetricAlgorithm mCSP = new TripleDESCryptoServiceProvider(); mCSP.Key = Encoding.UTF8.GetBytes(key); mCSP.IV = Encoding.UTF8.GetBytes(IV); ICryptoTransform ct; MemoryStream ms; CryptoStream cs; byte[] byt; ct = mCSP.CreateDecryptor(mCSP.Key, mCSP.IV); byt = Convert.FromBase64String(data); ms = new MemoryStream(); cs = new CryptoStream(ms, ct, CryptoStreamMode.Write); cs.Write(byt, 0, byt.Length); cs.FlushFinalBlock(); cs.Close(); return Encoding.UTF8.GetString(ms.ToArray()); } } }