c#實現驗證碼功能

來源:互聯網
上載者:User

一、驗證碼簡介
驗證碼功能一般是用於防止大量註冊的,不少網站為了防止使用者利用機器人自動註冊、登入、灌水,都採用了驗證碼技術。所謂驗證碼,就是將一串隨機產生的數字或字母或符號或文字,產生一幅圖片, 圖片裡加上一些幹擾象素(防止OCR),由使用者肉眼識別其中的驗證碼資訊,輸入表單提交網站驗證,驗證成功後才能使用某項功能。
常見的驗證碼有如下幾種:
1、純數字驗證碼,一般為四位隨機數字;
2、數字+字母驗證碼,一般從數字(0~9)和字母(A~Z和a~z)中隨機抽出幾個字元組成;
3、漢字驗證碼,相對而言,這種驗證碼比較少見一點,實現起來也相對複雜一些,但在不少網站中還是可以看到的;
二、驗證碼的實現
1、純數字驗證碼的實現
純數字驗證碼的實現相對比較簡單,可通過以下兩種方法來實現
(1)使用隨機數方式,代碼如下:

  1.         private String GetRandomint(int codeCount)
  2.         {
  3.             Random random = new Random();
  4.             string min = "";
  5.             string max = "";
  6.             for (int i = 0; i < codeCount; i++)
  7.             {
  8.                 min +="1";
  9.                 max+="9";
  10.             }
  11.                 return (random.Next(Convert.ToInt32(min),Convert.ToInt32(max)).ToString());
  12.         }

複製代碼

(2)使用隨機組合方式,代碼如下:

  1.         private string CreateRandomCode(int codeCount)
  2.         {
  3.             string allChar = "0,1,2,3,4,5,6,7,8,9";
  4.             string[] allCharArray = allChar.Split(',');
  5.             string randomCode = "";
  6.             int temp = -1;
  7.             Random rand = new Random();
  8.             for (int i = 0; i < codeCount; i++)
  9.             {
  10.                 if (temp != -1)
  11.                 {
  12.                     rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
  13.                 }
  14.                 int t = rand.Next(9);
  15.                 if (temp == t)
  16.                 {
  17.                     return CreateRandomCode(codeCount);
  18.                 }
  19.                 temp = t;
  20.                 randomCode += allCharArray[t];
  21.             }
  22.             return randomCode;
  23.         }

複製代碼

2、數字+字母驗證碼的實現,代碼如下:

  1.         private string CreateRandomCode(int codeCount)
  2.         {
  3.             string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
  4.             string[] allCharArray = allChar.Split(',');
  5.             string randomCode = "";
  6.             int temp = -1;
  7.             Random rand = new Random();
  8.             for (int i = 0; i < codeCount; i++)
  9.             {
  10.                 if (temp != -1)
  11.                 {
  12.                     rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
  13.                 }
  14.                 int t = rand.Next(61);
  15.                 if (temp == t)
  16.                 {
  17.                     return CreateRandomCode(codeCount);
  18.                 }
  19.                 temp = t;
  20.                 randomCode += allCharArray[t];
  21.             }
  22.             return randomCode;
  23.         }

複製代碼

3、漢字驗證碼的實現,代碼如下:

  1.         /**/
  2.         /*
  3.     此函數在漢字編碼範圍內隨機建立含兩個元素的十六進位位元組數組,每個位元組數組代表一個漢字,並將
  4.     四個位元組數組儲存在object數組中。
  5.     參數:strlength,代表需要產生的漢字個數
  6.     */
  7.         public static object[] CreateRegionCode(int strlength)
  8.         {
  9.             //定義一個字串數組儲存漢字編碼的組成元素
  10.             string[] rBase = new String[16] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
  11.             Random rnd = new Random();
  12.             //定義一個object數組用來
  13.             object[] bytes = new object[strlength];
  14.             /**/
  15.             /*每迴圈一次產生一個含兩個元素的十六進位位元組數組,並將其放入bject數組中
  16.         每個漢字有四個區位碼組成
  17.         區位碼第1位和區位碼第2位作為位元組數組第一個元素
  18.         區位碼第3位和區位碼第4位作為位元組數組第二個元素
  19.         */
  20.             for (int i = 0; i < strlength; i++)
  21.             {
  22.                 //區位碼第1位
  23.                 int r1 = rnd.Next(11, 14);
  24.                 string str_r1 = rBase[r1].Trim();
  25.                 //區位碼第2位
  26.                 rnd = new Random(r1 * unchecked((int)DateTime.Now.Ticks) + i);//更換隨機數發生器的種子避免產生重複值
  27.                 int r2;
  28.                 if (r1 == 13)
  29.                 {
  30.                     r2 = rnd.Next(0, 7);
  31.                 }
  32.                 else
  33.                 {
  34.                     r2 = rnd.Next(0, 16);
  35.                 }
  36.                 string str_r2 = rBase[r2].Trim();
  37.                 //區位碼第3位
  38.                 rnd = new Random(r2 * unchecked((int)DateTime.Now.Ticks) + i);
  39.                 int r3 = rnd.Next(10, 16);
  40.                 string str_r3 = rBase[r3].Trim();
  41.                 //區位碼第4位
  42.                 rnd = new Random(r3 * unchecked((int)DateTime.Now.Ticks) + i);
  43.                 int r4;
  44.                 if (r3 == 10)
  45.                 {
  46.                     r4 = rnd.Next(1, 16);
  47.                 }
  48.                 else if (r3 == 15)
  49.                 {
  50.                     r4 = rnd.Next(0, 15);
  51.                 }
  52.                 else
  53.                 {
  54.                     r4 = rnd.Next(0, 16);
  55.                 }
  56.                 string str_r4 = rBase[r4].Trim();
  57.                 //定義兩個位元組變數儲存產生的隨機漢字區位碼
  58.                 byte byte1 = Convert.ToByte(str_r1 + str_r2, 16);
  59.                 byte byte2 = Convert.ToByte(str_r3 + str_r4, 16);
  60.                 //將兩個位元組變數儲存在位元組數組中
  61.                 byte[] str_r = new byte[] { byte1, byte2 };
  62.                 //將產生的一個漢字的位元組數組放入object數組中
  63.                 bytes.SetValue(str_r, i);
  64.             }
  65.             return bytes;
  66.         }

複製代碼

三、具體執行個體
前台代碼display.aspx

  1. <body>
  2.     <form id="form1" runat="server">
  3.     <div>
  4.       <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
  5.         <asp:Image ID="Image1" runat="server" ImageUrl="png.aspx" /><br />
  6.         <br />
  7.       <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Button" />
  8.         <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
  9.             <asp:ListItem Value="3">預設</asp:ListItem>
  10.             <asp:ListItem Value="1">文字</asp:ListItem>
  11.             <asp:ListItem Value="2">數字</asp:ListItem>
  12.             <asp:ListItem Value="3">混合</asp:ListItem>
  13.         </asp:DropDownList></div>
  14.     </form>
  15. </body>

複製代碼

後台代碼display.cs

  1.         protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
  2.         {
  3.             switch (DropDownList1.SelectedValue)
  4.             {
  5.                 case "1":
  6.                     Image1.ImageUrl = "png.aspx?aa=1";
  7.                     break;
  8.                 case "2":
  9.                     Image1.ImageUrl = "png.aspx?aa=2";
  10.                     break;
  11.                 case "3":
  12.                     Image1.ImageUrl = "png.aspx?aa=3";
  13.                     break;
  14.             }
  15.         }
  16.         protected void Button2_Click(object sender, EventArgs e)
  17.         {
  18.             if (TextBox1.Text == Session["gif"].ToString())
  19.                 Response.Write("OK,正確");
  20.             else
  21.                 Response.Write("驗證碼不符合");
  22.         }

複製代碼

後台代碼png.cs

  1.     public partial class png : System.Web.UI.Page
  2.     {       
  3.         protected void Page_Load(object sender, EventArgs e)
  4.         {
  5.             switch (Request.QueryString["aa"])
  6.             {
  7.                 case "1":
  8.                     gif = stxt(10);
  9.                     Session["gif"] = stxt(10);
  10.                     break;
  11.                 case "2":
  12.                     gif = GetRandomint(4);
  13.                     Session["gif"] = GetRandomint(4);
  14.                     break;
  15.                 case "3":
  16.                     gif = CreateRandomCode(4);
  17.                     Session["gif"] = CreateRandomCode(4);
  18.                     break;
  19.                 default:
  20.                     gif = CreateRandomCode(4);
  21.                     Session["gif"] = CreateRandomCode(4);
  22.                     break;
  23.             }
  24.             CreateImage(Session["gif"].ToString());
  25.         }
  26.         private String GetRandomint(int codeCount)
  27.         {
  28.             Random random = new Random();
  29.             string min = "";
  30.             string max = "";
  31.             for (int i = 0; i < codeCount; i++)
  32.             {
  33.                 min +="1";
  34.                 max+="9";
  35.             }
  36.                 return (random.Next(Convert.ToInt32(min),Convert.ToInt32(max)).ToString());
  37.         }
  38.         /**/
  39.         /*
  40.     此函數在漢字編碼範圍內隨機建立含兩個元素的十六進位位元組數組,每個位元組數組代表一個漢字,並將
  41.     四個位元組數組儲存在object數組中。
  42.     參數:strlength,代表需要產生的漢字個數
  43.     */
  44.         public static object[] CreateRegionCode(int strlength)
  45.         {
  46.             //定義一個字串數組儲存漢字編碼的組成元素
  47.             string[] rBase = new String[16] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
  48.             Random rnd = new Random();
  49.             //定義一個object數組用來
  50.             object[] bytes = new object[strlength];
  51.             /**/
  52.             /*每迴圈一次產生一個含兩個元素的十六進位位元組數組,並將其放入bject數組中
  53.         每個漢字有四個區位碼組成
  54.         區位碼第1位和區位碼第2位作為位元組數組第一個元素
  55.         區位碼第3位和區位碼第4位作為位元組數組第二個元素
  56.         */
  57.             for (int i = 0; i < strlength; i++)
  58.             {
  59.                 //區位碼第1位
  60.                 int r1 = rnd.Next(11, 14);
  61.                 string str_r1 = rBase[r1].Trim();
  62.                 //區位碼第2位
  63.                 rnd = new Random(r1 * unchecked((int)DateTime.Now.Ticks) + i);//更換隨機數發生器的種子避免產生重複值
  64.                 int r2;
  65.                 if (r1 == 13)
  66.                 {
  67.                     r2 = rnd.Next(0, 7);
  68.                 }
  69.                 else
  70.                 {
  71.                     r2 = rnd.Next(0, 16);
  72.                 }
  73.                 string str_r2 = rBase[r2].Trim();
  74.                 //區位碼第3位
  75.                 rnd = new Random(r2 * unchecked((int)DateTime.Now.Ticks) + i);
  76.                 int r3 = rnd.Next(10, 16);
  77.                 string str_r3 = rBase[r3].Trim();
  78.                 //區位碼第4位
  79.                 rnd = new Random(r3 * unchecked((int)DateTime.Now.Ticks) + i);
  80.                 int r4;
  81.                 if (r3 == 10)
  82.                 {
  83.                     r4 = rnd.Next(1, 16);
  84.                 }
  85.                 else if (r3 == 15)
  86.                 {
  87.                     r4 = rnd.Next(0, 15);
  88.                 }
  89.                 else
  90.                 {
  91.                     r4 = rnd.Next(0, 16);
  92.                 }
  93.                 string str_r4 = rBase[r4].Trim();
  94.                 //定義兩個位元組變數儲存產生的隨機漢字區位碼
  95.                 byte byte1 = Convert.ToByte(str_r1 + str_r2, 16);
  96.                 byte byte2 = Convert.ToByte(str_r3 + str_r4, 16);
  97.                 //將兩個位元組變數儲存在位元組數組中
  98.                 byte[] str_r = new byte[] { byte1, byte2 };
  99.                 //將產生的一個漢字的位元組數組放入object數組中
  100.                 bytes.SetValue(str_r, i);
  101.             }
  102.             return bytes;
  103.         }
  104.         private string stxt(int num)
  105.         {
  106.             Encoding gb = Encoding.GetEncoding("gb2312");
  107.             //調用函數產生10個隨機中文漢字編碼
  108.             object[] bytes = CreateRegionCode(num);
  109.             string strtxt = "";
  110.             //根據漢字編碼的位元組數組解碼出中文漢字
  111.             for (int i = 0; i < num; i++)
  112.             {
  113.                 strtxt += gb.GetString((byte[])Convert.ChangeType(bytes, typeof(byte[])));
  114.             }
  115.             return strtxt;
  116.         }
  117.         /// <summary>
  118.         /// 這個是使用字母,數字混合
  119.         /// </summary>
  120.         /// <param name="VcodeNum"></param>
  121.         /// <returns></returns>
  122.         private string CreateRandomCode(int codeCount)
  123.         {
  124.             string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
  125.             string[] allCharArray = allChar.Split(',');
  126.             string randomCode = "";
  127.             int temp = -1;
  128.             Random rand = new Random();
  129.             for (int i = 0; i < codeCount; i++)
  130.             {
  131.                 if (temp != -1)
  132.                 {
  133.                     rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
  134.                 }
  135.                 int t = rand.Next(61);
  136.                 if (temp == t)
  137.                 {
  138.                     return CreateRandomCode(codeCount);
  139.                 }
  140.                 temp = t;
  141.                 randomCode += allCharArray[t];
  142.             }
  143.             return randomCode;
  144.         }
  145.         private void CreateImage(string checkCode)
  146.         {
  147.             int iwidth = (int)(checkCode.Length * 20);
  148.             System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 25);
  149.             Graphics g = Graphics.FromImage(image);
  150.             Font f = new System.Drawing.Font("Arial", 10, System.Drawing.FontStyle.Bold);
  151.             Brush b = new System.Drawing.SolidBrush(Color.White);
  152.             //g.FillRectangle(new System.Drawing.SolidBrush(Color.Blue),0,0,image.Width, image.Height);   
  153.             g.Clear(Color.Black);
  154.             g.DrawString(checkCode, f, b, 3, 3);
  155.             Pen blackPen = new Pen(Color.Black, 0);
  156.             Random rand = new Random();
  157.             //for (int i=0;i<5;i++)   
  158.             //{       
  159.             //    int y = rand.Next(image.Height); 
  160.             //    g.DrawLine(blackPen,0,y,image.Width,y);
  161.             //}       
  162.             System.IO.MemoryStream ms = new System.IO.MemoryStream();
  163.             image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
  164.             Response.ClearContent();
  165.             Response.ContentType = "image/Jpeg";
  166.             Response.BinaryWrite(ms.ToArray());
  167.             g.Dispose();
  168.             image.Dispose();
  169.         }
  170.     }

複製代碼

四、展示
驗證碼數字
附件: 2009012211325814.jpg
驗證碼數字+字母
附件: 2009012211340940.jpg
驗證碼漢字
附件: 2009012211350930.jpg

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.