1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4
5 namespace TravelB2B.Core.Utils.Text
6 {
7 /// <summary>
8 /// 产生随机中文验证码
9 /// </summary>
10 public class ChineseCode
11 {
12 /**/
13 /*
14 此函数在汉字编码范围内随机创建含两个元素的十六进制字节数组,每个字节数组代表一个汉字,并将
15 四个字节数组存储在object数组中。
16 参数:strlength,代表需要产生的汉字个数
17 */
18 private static object[] CreateRegionCode(int strlength)
19 {
20 //定义一个字符串数组储存汉字编码的组成元素
21 string[] rBase = new String[16] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
22
23 Random rnd = new Random();
24
25 //定义一个object数组用来
26 object[] bytes = new object[strlength];
27
28 /**/
29 /*每循环一次产生一个含两个元素的十六进制字节数组,并将其放入bject数组中
30 每个汉字有四个区位码组成
31 区位码第1位和区位码第2位作为字节数组第一个元素
32 区位码第3位和区位码第4位作为字节数组第二个元素
33 */
34 for (int i = 0; i < strlength; i++)
35 {
36 //区位码第1位
37 int r1 = rnd.Next(11, 14);
38 string str_r1 = rBase[r1].Trim();
39
40 //区位码第2位
41 rnd = new Random(r1 * unchecked((int)DateTime.Now.Ticks) + i);//更换随机数发生器的种子避免产生重复值
42 int r2;
43 if (r1 == 13)
44 {
45 r2 = rnd.Next(0, 7);
46 }
47 else
48 {
49 r2 = rnd.Next(0, 16);
50 }
51 string str_r2 = rBase[r2].Trim();
52
53 //区位码第3位
54 rnd = new Random(r2 * unchecked((int)DateTime.Now.Ticks) + i);
55 int r3 = rnd.Next(10, 16);
56 string str_r3 = rBase[r3].Trim();
57
58 //区位码第4位
59 rnd = new Random(r3 * unchecked((int)DateTime.Now.Ticks) + i);
60 int r4;
61 if (r3 == 10)
62 {
63 r4 = rnd.Next(1, 16);
64 }
65 else if (r3 == 15)
66 {
67 r4 = rnd.Next(0, 15);
68 }
69 else
70 {
71 r4 = rnd.Next(0, 16);
72 }
73 string str_r4 = rBase[r4].Trim();
74
75 //定义两个字节变量存储产生的随机汉字区位码
76 byte byte1 = Convert.ToByte(str_r1 + str_r2, 16);
77 byte byte2 = Convert.ToByte(str_r3 + str_r4, 16);
78 //将两个字节变量存储在字节数组中
79 byte[] str_r = new byte[] { byte1, byte2 };
80
81 //将产生的一个汉字的字节数组放入object数组中
82 bytes.SetValue(str_r, i);
83
84 }
85
86 return bytes;
87
88 }
89
90 public static string GetChinese(int length)
91 {
92 //获取GB2312编码页(表)
93 Encoding gb = Encoding.GetEncoding("gb2312");
94
95 //调用函数产生4个随机中文汉字编码
96 object[] bytes = CreateRegionCode(length);
97
98 //根据汉字编码的字节数组解码出中文汉字
99 StringBuilder sb = new StringBuilder();
100 for (int i = 0; i < length; i++)
101 {
102 sb.Append(gb.GetString((byte[])Convert.ChangeType(bytes[i], typeof(byte[]))));
103 }
104
105 //输出的控制台
106 return sb.ToString();
107 }
108
109 }
110 }