C# 对密码等数据进行对称性加密解密
类:
1 /// <summary> 2 /// DESEncrypt加密解密算法。 3 /// </summary> 4 public class DESEncrypt 5 { 6 private DESEncrypt() 7 { 8 // 9 // TODO: 在此处添加构造函数逻辑 10 // 11 } 12 13 //自定义口令 14 private static string key = "XluK7kDuA9yptTks"; 15 16 /// <summary> 17 /// 对称加密解密的密钥 18 /// </summary> 19 public static string Key 20 { 21 get 22 { 23 return key; 24 } 25 set 26 { 27 key = value; 28 } 29 } 30 31 /// <summary> 32 /// DES加密 33 /// </summary> 34 /// <param name="encryptString"></param> 35 /// <returns></returns> 36 public static string DesEncrypt(string encryptString) 37 { 38 try 39 { 40 byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 8)); 41 byte[] keyIV = keyBytes; 42 byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString); 43 DESCryptoServiceProvider provider = new DESCryptoServiceProvider(); 44 MemoryStream mStream = new MemoryStream(); 45 CryptoStream cStream = new CryptoStream(mStream, provider.CreateEncryptor(keyBytes, keyIV), CryptoStreamMode.Write); 46 cStream.Write(inputByteArray, 0, inputByteArray.Length); 47 cStream.FlushFinalBlock(); 48 return Convert.ToBase64String(mStream.ToArray()); 49 } 50 catch (Exception) 51 { 52 return ""; 53 } 54 } 55 56 /// <summary> 57 /// DES解密 58 /// </summary> 59 /// <param name="decryptString"></param> 60 /// <returns></returns> 61 public static string DesDecrypt(string decryptString) 62 { 63 try 64 { 65 byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 8)); 66 byte[] keyIV = keyBytes; 67 byte[] inputByteArray = Convert.FromBase64String(decryptString); 68 DESCryptoServiceProvider provider = new DESCryptoServiceProvider(); 69 MemoryStream mStream = new MemoryStream(); 70 CryptoStream cStream = new CryptoStream(mStream, provider.CreateDecryptor(keyBytes, keyIV), CryptoStreamMode.Write); 71 cStream.Write(inputByteArray, 0, inputByteArray.Length); 72 cStream.FlushFinalBlock(); 73 return Encoding.UTF8.GetString(mStream.ToArray()); 74 } 75 catch (Exception) 76 { 77 return ""; 78 } 79 } 80 }
调用:
1 //加密 2 string account=DESEncrypt.DesEncrypt(“account”); 3 //解密 4 account=DESEncrypt.DesDecrypt(account);