asp.net EncryptHelper 加密帮助类_实用技巧

分享到:

/**************************************************
* 版权所有: Mr_Sheng
* 文 件 名: EncryptHelper.cs
* 文件描述:
* 类型说明: EncryptHelper 加密帮助类
* 授权声明:
* 本程序为自由软件;
* 您可依据自由软件基金会所发表的GPL v3授权条款,对本程序再次发布和/或修改;
* 本程序是基于使用目的而加以发布,然而不负任何担保责任;
* 亦无对适售性或特定目的适用性所为的默示性担保。
* 详情请参照GNU通用公共授权 v3(参见license.txt文件)。
* 版本历史:
* v2.0.0 Mr_Sheng 2009-09-09 修改
*
***************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;

namespace Sheng.Common
{
/// <summary>
/// 加密帮助类
/// </summary>
public class EncryptHelper
{
/// <summary>
/// MD5加密
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string MD5DecryptString(string str)
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] md5Source = System.Text.Encoding.UTF8.GetBytes(str);
byte[] md5Out = md5.ComputeHash(md5Source);
return Convert.ToBase64String(md5Out);
}

/// <summary>
/// DES加密字符串
/// </summary>
/// <param name="sInputString">输入字符</param>
/// <param name="sKey">Key</param>
/// <returns>加密结果</returns>
public string DESEncryptString(string sInputString, string sKey)
{
try
{
byte[] data = Encoding.Default.GetBytes(sInputString);
byte[] result;
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey); //密钥
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey); //初始化向量
ICryptoTransform desencrypt = DES.CreateEncryptor(); //加密器对象
result = desencrypt.TransformFinalBlock(data, 0, data.Length); //转换指定字节数组的指定区域
return BitConverter.ToString(result);
}
catch (Exception ex)
{
//ex.Message = "DES加密异常";
throw ex;
}
}

/// <summary>
/// DES解密字符串
/// </summary>
/// <param name="sInputString">输入字符</param>
/// <param name="sKey">Key</param>
/// <returns>解密结果</returns>
public string DESDecryptString(string sInputString, string sKey)
{
try
{
//将字符串转换为字节数组
string[] sInput = sInputString.Split("-".ToCharArray());
byte[] data = new byte[sInput.Length];
byte[] result;
for (int i = 0; i < sInput.Length; i++)
{
data[i] = byte.Parse(sInput[i], System.Globalization.NumberStyles.HexNumber);
}

DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
ICryptoTransform desencrypt = DES.CreateDecryptor();
result = desencrypt.TransformFinalBlock(data, 0, data.Length);
return Encoding.Default.GetString(result);
}
catch (Exception ex)
{
//ex.Message = "DES解密异常";
throw ex;
}
}
}
}
昵    称:
验证码:

相关文档: