一个离开.NET的程序员

ryhan

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
 1 public static string GetShortUrl(string url)
 2         {
 3             //可以自定义生成MD5加密字符传前的混合KEY
 4             string key = DateTime.Now.ToString();
 5             //要使用生成URL的字符
 6             string[] chars = new string[]{           
 7              "a","b","c","d","e","f","g","h",
 8              "i","j","k","l","m","n","o","p",
 9              "q","r","s","t","u","v","w","x",
10              "y","z","0","1","2","3","4","5",
11              "6","7","8","9","A","B","C","D",
12              "E","F","G","H","I","J","K","L",
13              "M","N","O","P","Q","R","S","T",
14              "U","V","W","X","Y","Z"
15               };
16 
17             //对传入网址进行MD5加密
18             string hex = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(key + url, "md5");
19 
20             string[] resUrl = new string[4];
21             for (int i = 0; i < 4; i++)
22             {
23                 //把加密字符按照8位一组16进制与0x3FFFFFFF进行位与运算
24                 int hexint = 0x3FFFFFFF & Convert.ToInt32("0x" + hex.Substring(i * 8, 8), 16);
25                 string outChars = string.Empty;
26                 for (int j = 0; j < 6; j++)
27                 {
28                     //把得到的值与0x0000003D进行位与运算,取得字符数组chars索引
29                     int index = 0x0000003D & hexint;
30                     //把取得的字符相加
31                     outChars += chars[index];
32                     //每次循环按位右移5位
33                     hexint = hexint >> 5;
34                 }
35                 //把字符串存入对应索引的输出数组
36                 resUrl[i] = outChars;
37             }
38             return resUrl[new Random().Next(0, 3)];
39         }
View Code

 

posted on 2015-12-02 15:02  ryhan  阅读(3353)  评论(3编辑  收藏  举报