C#中MD5加密

View Code
 1 1using System;
 2 2using System.Collections.Generic;
 3 3using System.Text;
 4 4using System.Security.Cryptography;
 5 5
 6 6namespace md5
 7 7{
 8 8    class Program
 9 9    {
10 10        static void Main(string[] args)
11 11        {
12 12             Console.WriteLine(UserMd5("8"));
13 13             Console.WriteLine(GetMd5Str("8"));
14 14         }
15 15        /**//**/
16 16        /**//// <summary> 
17 17        /// MD5 16位加密 
18 18        /// </summary> 
19 19        /// <param name="ConvertString"></param> 
20 20        /// <returns></returns> 
21 21
22 22        public static string GetMd5Str(string ConvertString)
23 23        {
24 24             MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
25 25            string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8);
26 26             t2 = t2.Replace("-", "");
27 27            return t2;
28 28         }
29 29        /**//**/
30 30        /**//// <summary> 
31 31        /// MD5 32位加密 
32 32        /// </summary> 
33 33        /// <param name="str"></param> 
34 34        /// <returns></returns> 
35 35        static string UserMd5(string str)
36 36        {
37 37            string cl = str;
38 38            string pwd = "";
39 39             MD5 md5 = MD5.Create();//实例化一个md5对像 
40 40            // 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择  
41 41            byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl));
42 42            // 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得 
43 43            for (int i = 0; i < s.Length; i++)
44 44            {
45 45                // 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母,如果使用大写(X)则格式后的字符是大写字符 
46 46                 pwd = pwd + s[i].ToString("X");
47 47
48 48             }
49 49            return pwd;
50 50         }
51 51     }
52 52}
53 
54  
55 
56 方法二:
57 
58          /// <summary>
59         /// 对某一字符md5加密
60         /// </summary>
61         /// <param name="str"></param>
62         /// <param name="code">16与32位加密</param>
63         /// <returns></returns>
64         public static string MD5_Encrypt(string str, int code)
65         {
66             if (code == 16) //16位MD5加密(取32位加密的9~25字符) 
67             {
68                 return FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower().Substring(8, 16);
69             }
70             if (code == 32)
71             {
72                 return FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower();
73             }
74             return str;
75         }

 

posted @ 2012-10-31 21:55  brant_Man  阅读(249)  评论(0编辑  收藏  举报