////// Des和3Des算法 /// public class Des { ////// Des加密 /// /// 明文 /// 密钥 ///public static string DESEnCode(string pToEncrypt, string sKey) { pToEncrypt = HttpContext.Current.Server.UrlEncode(pToEncrypt); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] inputByteArray = Encoding.GetEncoding("UTF-8").GetBytes(pToEncrypt); des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); 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); } ret.ToString(); return ret.ToString(); } /// /// 3Des加密(密钥不能每8位重复,例如:123456781234567812345678,如果这样则算法退化为Des,C#会检测,不能使用) /// /// 明文 /// 密钥 ///public string Decrypt3DES(string a_strString, string a_strKey) { TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider(); DES.Key = ASCIIEncoding.ASCII.GetBytes(a_strKey); DES.Mode = CipherMode.ECB; DES.Padding = System.Security.Cryptography.PaddingMode.PKCS7; ICryptoTransform DESDecrypt = DES.CreateEncryptor(); string result = ""; try { byte[] Buffer = Convert.FromBase64String(a_strString); result = ASCIIEncoding.ASCII.GetString(DESDecrypt.TransformFinalBlock(Buffer, 0, Buffer.Length)); } catch (Exception e) { } return result; } /// /// Des解密 /// /// 密文 /// 密钥 ///public string Decrypt(string encryptedString, string key) { byte[] btKey = Encoding.UTF8.GetBytes(key); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); des.Key = ASCIIEncoding.ASCII.GetBytes(key); des.Mode = CipherMode.ECB; des.Padding = System.Security.Cryptography.PaddingMode.PKCS7; using (MemoryStream ms = new MemoryStream()) { byte[] inData = Convert.FromBase64String(encryptedString); try { using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(inData, 0, inData.Length); cs.FlushFinalBlock(); } return Encoding.UTF8.GetString(ms.ToArray()); } catch { return encryptedString; } } } /// /// 3Des解密(密钥不能每8位重复,例如:123456781234567812345678,如果这样则算法退化为Des,C#会检测,不能使用) /// /// 密文 /// 密钥 ///public string Decrypt3DES(string a_strString, string a_strKey) { TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider(); DES.Key = ASCIIEncoding.ASCII.GetBytes(a_strKey); DES.Mode = CipherMode.ECB; DES.Padding = System.Security.Cryptography.PaddingMode.PKCS7; ICryptoTransform DESDecrypt = DES.CreateDecryptor(); string result = ""; try { byte[] Buffer = Convert.FromBase64String(a_strString); result = ASCIIEncoding.ASCII.GetString(DESDecrypt.TransformFinalBlock(Buffer, 0, Buffer.Length)); } catch (Exception e) { } return result; } }