日期:2014-05-18  浏览次数:20929 次

怎么用C#加密一些数据
比如用户注册后的密码,怎么加密成MD5之类的?


------解决方案--------------------
using System;
using System.Text;
using System.Security.Cryptography;


/// <summary>
/// 根据输入的算法名进行运算,返回带字母的结果
/// </summary>
/// <param name= "value "> 进行加密的字符串 </param>
/// <param name= "EncryptName "> 算法名
/// 举例:MD5,SHA1,SHA256,SHA384,SHA512,RIPEMD160
/// </param>
/// <returns> 加密结果 </returns>
public static string EncryptValue(string value,string EncryptName)
{
byte[] hashvalue = (CryptoConfig.CreateFromName(EncryptName) as HashAlgorithm).ComputeHash(bytes(value));

StringBuilder text = new StringBuilder();
for (int i = 0, j = hashvalue.Length; i < j; i++)
text.Append(hashvalue[i].ToString( "x ").PadLeft(2, '0 '));
return text.ToString();
}

/// <summary>
/// 根据指定的值获取bytes
/// </summary>
/// <param name= "value "> 指定的值 </param>
/// <returns> bytes </returns>
public static byte[] bytes(string value)
{
return Encoding.ASCII.GetBytes(value);
}