1 /// <summary> 2 /// DES加密解密工具类 3 /// </summary> 4 public class DesUtil 5 { 6 /// <summary> 7 /// 秘钥 8 /// </summary> 9 private static string g_Key = "D228E0B3"; 10 11 /// <summary> 12 /// DES加密解密方法 13 /// </summary> 14 /// <param name="_String">加密解密字符串</param> 15 /// <param name="_Type">0:加密,1:解密</param> 16 /// <param name="_Key">Ksy</param> 17 /// <returns></returns> 18 public static bool DesFunction(ref string _String, E_Cipher _Type, params string[] _Key) 19 { 20 bool result = false; 21 if (_Key.Length != 0) 22 g_Key = _Key[0]; 23 24 switch (_Type) 25 { 26 case E_Cipher.Encrypt: 27 result = DesEncrypt(ref _String, g_Key); 28 break; 29 case E_Cipher.Decrypt: 30 result = DesDecrypt(ref _String, g_Key); 31 break; 32 } 33 return result; 34 } 35 36 /// <summary> 37 /// DES加密 38 /// </summary> 39 /// <param name="encryptString">需要加密的字符串</param> 40 /// <returns>加密后的字符串</returns> 41 private static bool DesEncrypt(ref string encryptString, string key) 42 { 43 try 44 { 45 byte[] keyBytes = Encoding.UTF8.GetBytes(key); 46 byte[] keyIV = keyBytes; 47 byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString); 48 DESCryptoServiceProvider provider = new DESCryptoServiceProvider(); 49 //直接加密 50 byte[] encrypted = provider.CreateEncryptor(keyBytes, keyIV).TransformFinalBlock(inputByteArray, 0, inputByteArray.Length); 51 encryptString = Convert.ToBase64String(encrypted); 52 return true; 53 } 54 catch (Exception _ex) 55 { 56 return false; 57 } 58 } 59 60 /// <summary> 61 /// DES解密 62 /// </summary> 63 /// <param name="decryptString">需要解密的字符串</param> 64 /// <returns>解密后的字符串</returns> 65 private static bool DesDecrypt(ref string decryptString, string key) 66 { 67 try 68 { 69 byte[] keyBytes = Encoding.UTF8.GetBytes(key); 70 byte[] keyIV = keyBytes; 71 byte[] inputByteArray = Convert.FromBase64String(decryptString); 72 DESCryptoServiceProvider provider = new DESCryptoServiceProvider(); 73 //直接解密 74 byte[] outputdata = provider.CreateDecryptor(keyBytes, keyIV).TransformFinalBlock(inputByteArray, 0, inputByteArray.Length); 75 decryptString = Encoding.UTF8.GetString(outputdata, 0, outputdata.Length); 76 return true; 77 } 78 catch (Exception _ex) 79 { 80 return false; 81 } 82 } 83 }
1 /// <summary> 2 /// 枚举类型 3 /// </summary> 4 public enum E_Cipher 5 { 6 /// <summary> 7 /// 加密 8 /// </summary> 9 Encrypt = 0, 10 /// <summary> 11 /// 解密 12 /// </summary> 13 Decrypt = 1 14 }
调用方式
/// <summary> /// 加密解密方法 /// </summary> public void DESEncryption() { string str = "12345"; bool result; //加密操作 result = DesUtil.DesFunction(ref str, E_Cipher.Encrypt); if (result) Console.WriteLine(str); //解密操作 result = DesUtil.DesFunction(ref str, E_Cipher.Decrypt); if (result) Console.WriteLine(str); }