日期:2014-05-17  浏览次数:21025 次

MD5加密的两种方法,一个是类似ASP中用的MD5加密方法,一个是类似JS中用的hex_md5加密方法

需要引用using System.Security.Cryptography;

方法一:类似ASP中的MD5加密方法

??????? /// <summary>
??????? /// 获取MD5加密后的字符串
??????? /// </summary>
??????? /// <param name="SourceString">需要加密的字符串</param>
??????? /// <param name="EncLen">加密数据长度,16位或者32位</param>
??????? /// <returns></returns>
??????? public static string MD5(string SourceString, int EncLen)
??????? {
??????????? MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
??????????? byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(SourceString));
??????????? StringBuilder sBuilder = new StringBuilder();
??????????? int i = 0;
??????????? if (EncLen == 16)
??????????? {
??????????????? for (i = 4; i <= 11; i++)
??????????????? {
??????????????????? sBuilder.Append(data[i].ToString("x2"));
??????????????? }
??????????? }
??????????? else
??????????? {
??????????????? for (i = 0; i <= 15; i++)
??????????????? {
??????????????????? sBuilder.Append(data[i].ToString("x2"));
??????????????? }
??????????? }
??????????? return sBuilder.ToString();
??????? }

?

方法二:类似JS中的hex_md5加密方法

??????? //JavaScript的hex_md5一样
??????? public static string CalculateMD5Hash(string input)
??????? {
??????????? // step 1, calculate MD5 hash from input
??????????? MD5 md5 = System.Security.Cryptography.MD5.Create();
??????????? byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
??????????? byte[] hash = md5.ComputeHash(inputBytes);

??????????? // step 2, convert byte array to hex string
??????????? StringBuilder sb = new StringBuilder();
??????????? for (int i = 0; i < hash.Length; i++)
??????????? {
??????????????? sb.Append(hash[i].ToString("X2"));
??????????? }
??????????? return sb.ToString();
??????? }