/// <summary>
/// HashEncryptor类:提供各种hash加密算法的实现
/// </summary>
/// <example>
/// //使用MD5加密
/// string data = "JGood";
/// string encryptedData = HashEncryptor.MD5(data);
/// </example>
/// <remarks>
/// HashEncryptor提供的加密算法都是不可逆的。
/// </remarks>
public sealed class HashEncryptor
{
/// <summary>
/// 私有
构造函数,该类不能被实例化
/// </summary>
private HashEncryptor()
{
}
/// <summary>
/// 使用MD5加密算法加密字符串
/// </summary>
/// <param name="data">要加密的字符串</param>
/// <returns>加密后的字符串</returns>
public static string MD5(string data)
{
return Encrypt("MD5", data);
}
/// <summary>
/// 使用SHA1加密算法加密字符串
/// </summary>
/// <param name="data">要加密的字符串</param>
/// <returns>加密后的字符串</returns>
public static string SHA1(string data)
{
return Encrypt("SHA1", data);
}
/// <summary>
/// 使用SHA 256位加密算法加密字符串
/// </summary>
/// <param name="data">要加密的字符串</param>
/// <returns>加密后的字符串</returns>
public static string SHA256(string data)
{
return Encrypt("SHA256", data);
}
/// <summary>
/// 使用SHA 384位加密算法加密字符串
/// </summary>
/// <param name="data">要加密的字符串</param>
/// <returns>加密后的字符串</returns>
public static string SHA384(string data)
{
return Encrypt("SHA384", data);
}
/// <summary>
/// 使用SHA 512位加密算法加密字符串
/// </summary>
/// <param name="data">要加密的字符串</param>
/// <returns>加密后的字符串</returns>
public static string SHA512(string data)
{
return Encrypt("SHA512", data);
}
/// <summary>
/// 按指定加密算法,对字符串进行加密
/// </summary>
/// <param name="hashName">加密算法名称</param>
/// <param name="data">要加密数据</param>
/// <returns>加密后的数据</returns>
private static string Encrypt(string hashName, string data)
{
byte[] btData = System.Text.Encoding.ASCII.GetBytes(data);
//创建一个 HashAlgorithm派生类的实例
HashAlgorithm hasher = HashAlgorithm.Create(hashName);
//使用hash加密
byte[] hashedData = hasher.ComputeHash(btData);
StringBuilder result = new StringBuilder();
foreach (byte b in hashedData)
{
result.Append(b.ToString("x2")); //转换成16进制保存
}
return result.ToString();
}
}