using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace Char.common
{
public static class DataEncrypt
{
#region MD5 加密
/// <summary>
/// MD5 加密静态方法 不可逆
/// </summary>
/// <param name="EncryptString">待加密的密文</param>
/// <returns>returns</returns>
public static string MD5Encrypt(string EncryptString)
{
if (string.IsNullOrEmpty(EncryptString)) { throw (new Exception("密文不得为空")); }
MD5 m_ClassMD5 = new MD5CryptoServiceProvider();
string m_strEncrypt = "";
try
{
m_strEncrypt = BitConverter.ToString(m_ClassMD5.ComputeHash(Encoding.Default.GetBytes(EncryptString))).Replace("-", "");
}
catch (ArgumentException ex) { throw ex; }
catch (CryptographicException ex) { throw ex; }
catch (Exception ex) { throw ex; }
finally { m_ClassMD5.Clear(); }
return m_strEncrypt;
}
#endregion
#region DES 加密解密
public static string DES_Key = "tb_zz_rj";//秘钥 固定8位
/// <summary>
/// DES加密
/// </summary>
/// <param name="pToEncrypt"></param>
/// <returns></returns>
public static string DESEncrypt(string pToEncrypt)
{
//pToEncrypt = HttpContext.Current.Server.UrlEncode(pToEncrypt);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = Encoding.GetEncoding("UTF-8").GetBytes(pToEncrypt);
des.Key = ASCIIEncoding.ASCII.GetBytes(DES_Key);
des.IV = ASCIIEncoding.ASCII.GetBytes(DES_Key);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
StringBuilder ret = new StringBuilder();
foreach (byte b in ms.ToArray())
{
ret.AppendFormat("{0:X2}", b);
}
ret.ToString();
return ret.ToString();
}
/// <summary>
/// DES解密
/// </summary>
/// <param name="pToDecrypt"></param>
/// <returns></returns>
public static string DESDecrypt(string pToDecrypt)
{
try
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
for (int x = 0; x < pToDecrypt.Length / 2; x++)
{
int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
inputByteArray[x] = (byte)i;
}
des.Key = ASCIIEncoding.ASCII.GetBytes(DES_Key);
des.IV = ASCIIEncoding.ASCII.GetBytes(DES_Key);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
StringBuilder ret = new StringBuilder();
return System.Text.Encoding.Default.GetString(ms.ToArray());
}
catch (Exception)
{
return "";
}
}
#endregion
}
}