md5 加密

web和windows应用程序都能用的,适合写进公共类库里面,代码是参考2.0类库的  System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile
System.Web.Configuration.MachineKeySection.ByteArrayToHexString
这两个方法,基本上没作改动,只是把不安全代码换掉了

29行的 0x61 改成 0x41 生成的就是大写字符的了

 1private static char[] s_acharval;
 2public static string MD5(string password)
 3{
 4    if ((password == null|| (password.Length == 0))
 5    {
 6        password = string.Empty;
 7    }

 8    byte[] bytes = Encoding.UTF8.GetBytes(password);
 9    MD5 md5 = new MD5CryptoServiceProvider();
10    byte[] buffer = md5.ComputeHash(bytes);
11    return ByteArrayToHexString(buffer, 0);
12}

13
14internal static string ByteArrayToHexString(byte[] buf, int iLen)
15{
16    char[] chArray = s_acharval;
17    if (chArray == null)
18    {
19        chArray = new char[0x10];
20        int length = chArray.Length;
21        while (--length >= 0)
22        {
23            if (length < 10)
24            {
25                chArray[length] = (char)(0x30 + length);
26            }

27            else
28            {
29                chArray[length] = (char)(0x61 + (length - 10));
30            }

31        }

32        s_acharval = chArray;
33    }

34    if (buf == null)
35    {
36        return null;
37    }

38    if (iLen == 0)
39    {
40        iLen = buf.Length;
41    }

42    char[] chArray2 = new char[iLen * 2];
43    for (int i = 0, j = 0--iLen >= 0; i++)
44    {
45        chArray2[j] = chArray[(buf[i] & 240>> 4];
46        j++;
47        chArray2[j] = chArray[buf[i] & 15];
48        j++;
49    }

50    return new string(chArray2);
51}
posted @ 2008-01-02 14:04  wpg  阅读(271)  评论(0)    收藏  举报