1 using System; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Linq; 5 using System.Security.Cryptography; 6 using System.Text; 7 using System.Threading.Tasks; 8 9 namespace MyEncrypt 10 { 11 /// <summary> 12 /// DES AES Blowfish 13 /// 对称加密算法的优点是速度快, 14 /// 缺点是密钥管理不方便,要求共享密钥。 15 /// 可逆对称加密 密钥长度8 16 /// </summary> 17 public class DesEncrypt 18 { 19 private static byte[] _rgbKey = ASCIIEncoding.ASCII.GetBytes(Constant.DesKey.Substring(0, 8)); 20 private static byte[] _rgbIV = ASCIIEncoding.ASCII.GetBytes(Constant.DesKey.Insert(0, "w").Substring(0, 8)); 21 22 /// <summary> 23 /// DES 加密 24 /// </summary> 25 /// <param name="text">需要加密的值</param> 26 /// <returns>加密后的结果</returns> 27 public static string Encrypt(string text) 28 { 29 DESCryptoServiceProvider dsp = new DESCryptoServiceProvider(); 30 using (MemoryStream memStream = new MemoryStream()) 31 { 32 CryptoStream crypStream = new CryptoStream(memStream, dsp.CreateEncryptor(_rgbKey, _rgbIV), CryptoStreamMode.Write); 33 StreamWriter sWriter = new StreamWriter(crypStream); 34 sWriter.Write(text); 35 sWriter.Flush(); 36 crypStream.FlushFinalBlock(); 37 memStream.Flush(); 38 return Convert.ToBase64String(memStream.GetBuffer(), 0, (int)memStream.Length); 39 } 40 } 41 42 /// <summary> 43 /// DES解密 44 /// </summary> 45 /// <param name="encryptText"></param> 46 /// <returns>解密后的结果</returns> 47 public static string Decrypt(string encryptText) 48 { 49 DESCryptoServiceProvider dsp = new DESCryptoServiceProvider(); 50 byte[] buffer = Convert.FromBase64String(encryptText); 51 52 using (MemoryStream memStream = new MemoryStream()) 53 { 54 CryptoStream crypStream = new CryptoStream(memStream, dsp.CreateDecryptor(_rgbKey, _rgbIV), CryptoStreamMode.Write); 55 crypStream.Write(buffer, 0, buffer.Length); 56 crypStream.FlushFinalBlock(); 57 return ASCIIEncoding.UTF8.GetString(memStream.ToArray()); 58 } 59 } 60 } 61 }