using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.IO;
using System.Text;
namespace DBUtility
{
/// <summary>
/// 加密类
/// </summary>
public class Encrypt
{
/// <summary>
/// Has加密
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string HashBase64(string str)
{
byte[] result = new byte[str.Length];
try
{
SHA1 sha = new SHA1CryptoServiceProvider();
result = sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(str));
return Convert.ToBase64String(result);
}
catch
{
return "加密失败!";
}
}
/// <summary>
/// 密码加密
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string Md5PassWord(string str)
{
return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower().Substring(8, 16);
}
private static string key = "sohomake";
/// <summary>
/// DES加密
/// </summary>
/// <param name="strText">要加密的字符串</param>
/// <param name="key">加密密钥(8位)</param>
/// <returns></returns>
public static string DesEncrypt(string strText)
{
byte[] byKey = null;
byte[] IV = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF };
try
{
byKey = System.Text.Encoding.UTF8.GetBytes(key);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = Encoding.UTF8.GetBytes(strText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
cs.Close();
return Convert.ToBase64String(ms.ToArray());
}
catch (System.Exception error)
{
return "error:" + error.Message + "/r";
}
}
/// <summary>
/// DES解密
/// </summary>
/// <param name="strText">要解密的字符串</param>
/// <param name="key">解密密钥(8位)</param>
/// <returns></returns>
public static string DesDecrypt(string strText)
{
byte[] byKey = null;
byte[] IV = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF };
byte[] inputByteArray = Convert.FromBase64String(strText);
try
{
byKey = System.Text.Encoding.UTF8.GetBytes(key);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
inputByteArray = Convert.FromBase64String(strText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
cs.Close();
return Encoding.UTF8.GetString(ms.ToArray());
}
catch (System.Exception error)
{
return "error:" + error.Message + "/r";
}
}
}
}