自己写的DES加密解密类,加密后生成Base64字符串,并去除'='字符。
加密后替换掉'+',这样加密后的字符串可以作为url参数传递。
using System;using System.IO;using System.Security.Cryptography;using System.Text;namespace QuaEdu.Helper{ ////// DES加密/解密类。 /// 2014年3月15日 /// public class DESHelper { #region 默认密钥 ////// 默认密钥 /// private static readonly string m_key = "simpo_s0611163"; #endregion #region ========加密======== ////// 加密数据 /// /// 原文 ///密文 public static string Encrypt(string Text) { return Encrypt(Text, m_key); } ////// 加密数据 /// /// 原文 /// 密钥 ///密文 public static string Encrypt(string Text, string sKey) { DESCryptoServiceProvider desKey = new DESCryptoServiceProvider(); byte[] inputByteArray = Encoding.Default.GetBytes(Text); byte[] keyByteArray = Encoding.Default.GetBytes(sKey); MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); md5.ComputeHash(keyByteArray); desKey.Key = HalveByteArray(md5.Hash); desKey.IV = HalveByteArray(md5.Hash); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, desKey.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); return Convert.ToBase64String(ms.ToArray()).Replace("=", "").Replace("+", "-").Replace("/", "*"); } #endregion #region ========解密======== ////// 解密数据 /// /// 密文 ///原文 public static string Decrypt(string Text) { return Decrypt(Text, m_key); } ////// 解密数据 /// /// 密文 /// 密钥 ///原文 public static string Decrypt(string Text, string sKey) { StringBuilder sb = new StringBuilder(); if (Text.Length % 4 != 0) { for (int i = 0; i < 4 - Text.Length % 4; i++) { sb.Append("="); } } Text = Text.Replace("-", "+").Replace("*", "/") + sb.ToString(); DESCryptoServiceProvider desKey = new DESCryptoServiceProvider(); byte[] inputByteArray = Convert.FromBase64String(Text); byte[] keyByteArray = Encoding.Default.GetBytes(sKey); MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); md5.ComputeHash(keyByteArray); desKey.Key = HalveByteArray(md5.Hash); desKey.IV = HalveByteArray(md5.Hash); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, desKey.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); return Encoding.Default.GetString(ms.ToArray()); } #endregion #region 把字节数组缩短一半 ////// 把字节数组缩短一半 /// private static byte[] HalveByteArray(byte[] data) { byte[] result = new byte[data.Length / 2]; for (int i = 0; i < result.Length; i++) { int x = (data[i * 2] + data[i * 2 + 1]) / 2; result[i] = (byte)x; } return result; } #endregion }}