region 加密数据 /// <summary> /// 加密数据 /// 如秘钥为空 则返回原文 /// </summary> /// <param name="content">加密前文本</param> /// <param name="desKey">密匙</param> /// <returns></returns> public static string EncryptStr(string content, string desKey) { try { if (string.IsNullOrEmpty(desKey)) { return content; } DESCryptoServiceProvider des = new DESCryptoServiceProvider(); des.Mode = CipherMode.ECB; var keys = new byte[8]; if (desKey.Length < 8) { var tmpkeys = System.Text.Encoding.UTF8.GetBytes(desKey); for (int i = 0; i < keys.Length; i++) { if (tmpkeys.Length > i) keys[i] = tmpkeys[i]; else keys[i] = 0; } } else keys = System.Text.Encoding.UTF8.GetBytes(desKey.Substring(0, 8)); des.Key = keys; des.IV = des.Key; byte[] inputByteArray = System.Text.Encoding.UTF8.GetBytes(content); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); StringBuilder sb = new StringBuilder(); foreach (var item in ms.ToArray()) { sb.Append(item.ToString()); sb.Append("_"); } if (sb.Length > 0) { sb = sb.Remove(sb.Length - 1, 1); } return sb.ToString(); } catch (System.Exception e) { return content; } } #endregion
#region 解密数据 /// <summary> /// 解密数据 /// 如秘钥为空 则返回原文 /// </summary> /// <param name="content">密文</param> /// <param name="desKey">密匙</param> /// <returns>解密失败返回空字符串</returns> public static string DecryptStr(string content, string desKey) { try { if (string.IsNullOrEmpty(desKey)) { return content; } DESCryptoServiceProvider des = new DESCryptoServiceProvider(); des.Mode = CipherMode.ECB; var keys = new byte[8]; if (desKey.Length < 8) { var tmpkeys = System.Text.Encoding.UTF8.GetBytes(desKey); for (int i = 0; i < keys.Length; i++) { if (tmpkeys.Length > i) keys[i] = tmpkeys[i]; else keys[i] = 0; } } else keys = System.Text.Encoding.UTF8.GetBytes(desKey.Substring(0, 8)); des.Key = keys; des.IV = des.Key; var data = content.Split('_'); byte[] inputByteArray = new byte[data.Length]; ;//Convert.FromBase64String(encryptText); for (int i = 0; i < data.Length; i++) { inputByteArray[i] = Convert.ToByte(data[i]); } MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); System.Text.Encoding encoding = new System.Text.UTF8Encoding(); return encoding.GetString(ms.ToArray()); } catch (System.Exception e) { return ""; } } #endregion