string扩展实现强悍的.Net不可逆加密方法 (转载)
最近写加密方法,发现同类的加密方法的基类都是一直的,用泛型整合了一些加密方法,供大家参考
实现方法:
Code
using System;
using System.Text;
using System.Security.Cryptography;
namespace Zb
{
public static class StringExtensions
{
/// <summary>
/// 不可逆加密
/// </summary>
/// <typeparam name="Algorithm">加密HASH算法</typeparam>
/// <typeparam name="StringEncoding">字符编码</typeparam>
/// <param name="str"></param>
/// <returns></returns>
public static string EncryptOneWay<Algorithm, StringEncoding>(this string str)
where Algorithm : HashAlgorithm
where StringEncoding : Encoding
{
Encoding enco = Activator.CreateInstance<StringEncoding>();
byte[] inputBye = enco.GetBytes(str);
byte[] bytes = Activator.CreateInstance<Algorithm>().ComputeHash(inputBye);
return System.BitConverter.ToString(bytes).Replace("-", ""); ;
}
/// <summary>
/// 不可逆加密
/// </summary>
/// <typeparam name="Algorithm">加密HASH算法</typeparam>
/// <param name="str">字符编码</param>
/// <returns></returns>
public static string EncryptOneWay<Algorithm>(this string str)
where Algorithm : HashAlgorithm
{
return str.EncryptOneWay<Algorithm, System.Text.UTF8Encoding>();
}
}
}
using System;
using System.Text;
using System.Security.Cryptography;
namespace Zb
{
public static class StringExtensions
{
/// <summary>
/// 不可逆加密
/// </summary>
/// <typeparam name="Algorithm">加密HASH算法</typeparam>
/// <typeparam name="StringEncoding">字符编码</typeparam>
/// <param name="str"></param>
/// <returns></returns>
public static string EncryptOneWay<Algorithm, StringEncoding>(this string str)
where Algorithm : HashAlgorithm
where StringEncoding : Encoding
{
Encoding enco = Activator.CreateInstance<StringEncoding>();
byte[] inputBye = enco.GetBytes(str);
byte[] bytes = Activator.CreateInstance<Algorithm>().ComputeHash(inputBye);
return System.BitConverter.ToString(bytes).Replace("-", ""); ;
}
/// <summary>
/// 不可逆加密
/// </summary>
/// <typeparam name="Algorithm">加密HASH算法</typeparam>
/// <param name="str">字符编码</param>
/// <returns></returns>
public static string EncryptOneWay<Algorithm>(this string str)
where Algorithm : HashAlgorithm
{
return str.EncryptOneWay<Algorithm, System.Text.UTF8Encoding>();
}
}
}
使用方法:
1 MD5 :
string temp = "123".EncryptOneWay<System.Security.Cryptography.MD5CryptoServiceProvider, System.Text.UTF8Encoding>();
2. sha1:
string temp = "123".EncryptOneWay<System.Security.Cryptography.SHA1CryptoServiceProvider>();
3 SHA256
string temp = "123".EncryptOneWay<System.Security.Cryptography.SHA256Cng>();
等所有的HASH算法都可以用