加解密2-字符串
加密字符串:
1 /// <summary> 2 /// DES加密字符串 3 /// 加密密钥,要求为8位 4 /// 加密成功返回加密后的字符串,失败返回源串 5 /// </summary> 6 /// <param name="encryptString">待加密的字符串</param> 7 /// <param name="decryptIV">加密因子</param> 8 /// <param name="encryptKey">加密密钥,要求为8位</param> 9 /// <returns> 加密成功返回加密后的字符串,失败返回源串</returns> 10 public static string EncryptDES(string encryptString, string encryptIV, string encryptKey) 11 { 12 try 13 { 14 byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8)); 15 byte[] rgbIV = Encoding.UTF8.GetBytes(encryptIV.Substring(0, 8)); 16 byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString); 17 DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider(); 18 19 MemoryStream mStream = new MemoryStream(); 20 //加密方式写入到mSteram 21 CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write); 22 cStream.Write(inputByteArray, 0, inputByteArray.Length); 23 cStream.FlushFinalBlock(); 24 return Convert.ToBase64String(mStream.ToArray()); 25 } 26 catch 27 { 28 return encryptString;//异常返回原始字符串 29 } 30 }
解密字符串:
1 /// <summary> 2 /// DES解密字符串 3 /// 解密密钥,要求为8位,和加密密钥相同 4 /// 解密成功返回解密后的字符串,失败返源串 5 /// </summary> 6 /// <param name="decryptString">待解密的字符串</param> 7 /// <param name="decryptIV">解密因子</param> 8 /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param> 9 /// <returns>解密成功返回解密后的字符串,失败返源串</ 10 public static string DecryptDES(string decryptString,string decryptIV,string decryptKey) 11 { 12 try 13 { 14 byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey.Substring(0, 8)); 15 byte[] rgbIV = Encoding.UTF8.GetBytes(decryptIV.Substring(0, 8)); 16 byte[] inputByteArray = Convert.FromBase64String(decryptString); 17 18 //算法 19 DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider(); 20 21 //基础流 22 MemoryStream mStream = new MemoryStream(); 23 24 //以解密方式写入mStream 25 CryptoStream cStream = new CryptoStream(mStream,DCSP.CreateDecryptor(rgbKey,rgbIV),CryptoStreamMode.Write); 26 cStream.Write(inputByteArray, 0, inputByteArray.Length); 27 cStream.FlushFinalBlock(); 28 29 return Encoding.UTF8.GetString(mStream.ToArray()); 30 } 31 catch 32 { 33 return decryptString;//异常返回原始字符串 34 } 35 }