ASP.NET1.1验证码产生的原理及应用

开发 后端
文章介绍了asp.net1.1中验证码产生的原理及应用。实现原理就是,通过随机函数产生验证码元素,将数值型的验证码元素转换成字符型然后再连成字符串,将验证码字符串写入Cookie以供验证时调用。

ASP.NET1.1验证码实现原理

通过随机函数产生验证码元素,将数值型的验证码元素转换成字符型然后再连成字符串,将验证码字符串写入Cookie以供验证时调用。

通过后台动态绘制位图的方法,绘制一个指定大小的位图,然后在空白位图画出底纹、验证码字体、和边框。

ASP.NET1.1验证码实现代码

(1)Login.aspx(登录页前台)

  1. < %@ Page language="c#" Codebehind="Login.aspx.cs" AutoEventWireup="false" Inherits="Validator.Login" %>  
  2. < !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >  
  3. < HTML>  
  4.     < HEAD>  
  5.         < title>Login< /title>  
  6.         < meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">  
  7.         < meta name="CODE_LANGUAGE" Content="C#">  
  8.         < meta name="vs_defaultClientScript" content="JavaScript">  
  9.         < meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">  
  10.     < /HEAD>  
  11.     < body MS_POSITIONING="GridLayout">  
  12.         < form id="Form1" method="post" runat="server">  
  13.             < asp:button id="Button1" style="Z-INDEX: 101; LEFT: 128px; POSITION: absolute; TOP: 64px" runat="server" 
  14.                 Width="96px" Text="提交">< /asp:button>  
  15.             < IMG src="CheckCode.aspx">  
  16.             < asp:label id="lblMessage" style="Z-INDEX: 102; LEFT: 16px; POSITION: absolute; TOP: 128px" 
  17.                 runat="server">< /asp:label>  
  18.             < asp:textbox id="txtCheckCode" style="Z-INDEX: 103; LEFT: 16px; POSITION: absolute; TOP: 64px" 
  19.                 runat="server" Width="88px">< /asp:textbox>  
  20.         < /form>  
  21.     < /body>  
  22. < /HTML>  

(2)Login.aspx.cs(登录页后台)

  1. using System;  
  2. using System.Collections;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Web;  
  7. using System.Web.SessionState;  
  8. using System.Web.UI;  
  9. using System.Web.UI.WebControls;  
  10. using System.Web.UI.HtmlControls;  
  11.  
  12. namespace Validator  
  13. {  
  14.     /**//// < summary>  
  15.     /// Login 的摘要说明。  
  16.     /// < /summary>  
  17.     public class Login : System.Web.UI.Page  
  18.     {  
  19.         protected System.Web.UI.WebControls.Button Button1;  
  20.         protected System.Web.UI.WebControls.Label lblMessage;  
  21.         protected System.Web.UI.WebControls.TextBox txtCheckCode;  
  22.       
  23.         private void Page_Load(object sender, System.EventArgs e)  
  24.         {  
  25.             // 在此处放置用户代码以初始化页面  
  26.         }  
  27.  
  28.         Web 窗体设计器生成的代码#region Web 窗体设计器生成的代码  
  29.         override protected void OnInit(EventArgs e)  
  30.         {  
  31.             //  
  32.             // CODEGEN: 该调用是 asp.net Web 窗体设计器所必需的。  
  33.             //  
  34.             InitializeComponent();  
  35.             base.OnInit(e);  
  36.         }  
  37.           
  38.         /**//// < summary>  
  39.         /// 设计器支持所需的方法 - 不要使用代码编辑器修改  
  40.         /// 此方法的内容。  
  41.         /// < /summary>  
  42.         private void InitializeComponent()  
  43.         {      
  44.             this.Button1.Click += new System.EventHandler(this.Button1_Click);  
  45.             this.Load += new System.EventHandler(this.Page_Load);  
  46.  
  47.         }  
  48.         #endregion  
  49.  
  50.         private void Button1_Click(object sender, System.EventArgs e)  
  51.         {  
  52.             if(Request.Cookies["CheckCode"] == null)   
  53.             {  
  54.                 lblMessage.Text = "您的浏览器设置已被禁用 Cookies,您必须设置浏览器允许使用 Cookies 选项后才能使用本系统。";  
  55.                 lblMessage.Visible = true;  
  56.                 return;  
  57.             }  
  58.             if(String.Compare(Request.Cookies["CheckCode"].Value, txtCheckCode.Text, false) != 0) //参数为false时为区分大小写  
  59.             {  
  60.                 lblMessage.Text = "验证码错误,请输入正确的验证码。";  
  61.                 lblMessage.Visible = true;  
  62.                 return;  
  63.             }   
  64.             else   
  65.             {  
  66.                 lblMessage.Text = "通过验证";  
  67.                 lblMessage.Visible = true;  
  68.                 return;  
  69.             }  
  70.         }  
  71.     }  
  72. }  
  73.  

(3) CheckCode.aspx(验证页前台)

  1. < %@ Page language="c#" Codebehind="CheckCode.aspx.cs" AutoEventWireup="false" Inherits="Validator.CheckCode" %>  
  2. < !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >   
  3.  
  4. < html>  
  5.   < head>  
  6.     < title>CheckCode< /title>  
  7.     < meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">  
  8.     < meta name="CODE_LANGUAGE" Content="C#">  
  9.     < meta name=vs_defaultClientScript content="JavaScript">  
  10.     < meta name=vs_targetSchema content="http://schemas.microsoft.com/intellisense/ie5">  
  11.   < /head>  
  12.   < body MS_POSITIONING="GridLayout">  
  13.       
  14.     < form id="Form1" method="post" runat="server">  
  15.         < FONT face="宋体">< /FONT>  
  16.     < /form>  
  17.       
  18.   < /body>  
  19. < /html>  
  20.  

(4)CheckCode.aspx.cs(验证页后台)

  1. using System;  
  2. using System.Collections;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Web;  
  7. using System.Web.SessionState;  
  8. using System.Web.UI;  
  9. using System.Web.UI.WebControls;  
  10. using System.Web.UI.HtmlControls;  
  11.  
  12. namespace Validator  
  13. {  
  14.     /**//// < summary>  
  15.     /// CheckCode 的摘要说明。  
  16.     /// < /summary>  
  17.     public class CheckCode : System.Web.UI.Page  
  18.     {  
  19.         private void Page_Load(object sender, System.EventArgs e)  
  20.         {  
  21.             // 在此处放置用户代码以初始化页面  
  22.             this.CreateCheckCodeImage(GenerateCheckCode());  
  23.         }  
  24.  
  25.         Web 窗体设计器生成的代码#region Web 窗体设计器生成的代码  
  26.         override protected void OnInit(EventArgs e)  
  27.         {  
  28.             //  
  29.             // CODEGEN: 该调用是 asp.net Web 窗体设计器所必需的。  
  30.             //  
  31.             InitializeComponent();  
  32.             base.OnInit(e);  
  33.         }  
  34.           
  35.         /**//// < summary>  
  36.         /// 设计器支持所需的方法 - 不要使用代码编辑器修改  
  37.         /// 此方法的内容。  
  38.         /// < /summary>  
  39.         private void InitializeComponent()  
  40.         {      
  41.             this.Load += new System.EventHandler(this.Page_Load);  
  42.         }  
  43.         #endregion  
  44.  
  45.         private string GenerateCheckCode()  
  46.         {                        
  47.             int number;                        
  48.             char code;                        
  49.             string checkCode = String.Empty;                                     
  50.             System.Random random = new Random();                         
  51.             for(int i=0; i< 5; i++)                        
  52.             {   //随机产生一个整数                               
  53.                 number = random.Next();                   
  54.                 //如果随机数是偶数 取余选择从[0-9]                               
  55.                 if(number % 2 == 0)                                      
  56.                     code = (char)('0' + (char)(number % 10));                               
  57.                 else                               
  58.                 //如果随机数是奇数 选择从[A-Z]                                      
  59.                     code = (char)('A' + (char)(number % 26));                                
  60.                     checkCode += code.ToString();                        
  61.             }                         
  62.             Response.Cookies.Add(new HttpCookie("CheckCode", checkCode));                         
  63.             return checkCode;                 
  64.         }           
  65.  
  66.         //建立一个随机图形                 
  67.         private void CreateCheckCodeImage(string checkCode)                 
  68.         {                        
  69.             if(checkCode == null || checkCode.Trim() == String.Empty)                               
  70.                 return;               
  71.             //建立一个位图文件 确立长宽                                         
  72.             System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);                        
  73.             Graphics g = Graphics.FromImage(image);                         
  74.             try                        
  75.             {                               
  76.                 //生成随机生成器                               
  77.                 Random random = new Random();                                
  78.                 //清空图片背景色                               
  79.                 g.Clear(Color.White);                                
  80.                 //画图片的背景噪音点                               
  81.                 for(int i=0; i< 60; i++)                               
  82.                 {                                      
  83.                     int x = random.Next(image.Width);                                      
  84.                     int y = random.Next(image.Height);                                       
  85.                     image.SetPixel(x, y, Color.FromArgb(random.Next()));                               
  86.                 }                   
  87.                 //把产生的随机数以字体的形式写入画面                               
  88.                 Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));                               
  89.                 System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);                               
  90.                 g.DrawString(checkCode, font, brush, 2, 2);                                
  91.                 //画图片的边框线                               
  92.                 g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);                                
  93.                 System.IO.MemoryStream ms = new System.IO.MemoryStream();                               
  94.                 image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);                               
  95.                 Response.ClearContent();                               
  96.                 Response.ContentType = "image/Gif";                               
  97.                 Response.BinaryWrite(ms.ToArray());                        
  98.             }                        
  99.             finally                        
  100.             {                               
  101.                 g.Dispose();                               
  102.                 image.Dispose();                        
  103.             }                 
  104.         }  
  105.     }  
  106. }  
  107.  

ASP.NET1.1验证码主要函数分析

1、通过随机函数(Random)先产生验证码组成元素(这里为五位) 并将其转换为字符串(属性为只读),完成后写入“Cookie”中去以供验证时调用。

2、将验证码字符串写入图形:

(1)建立一个位图文件确定长和宽:

  1. System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);   

(a)System.Drawing. [C#] Bitmap(int width,int height);

(b)double Math.Ceiling (double a):返回大于或等于指定数字的最小整数。

(2)画图片的背景噪音点(60个):

  1. for(int i=0; i< 60; i++)  {   
  2. int x = random.Next(image.Width);   
  3. int y = random.Next(image.Height);   
  4. image.SetPixel(x, y, Color.FromArgb(random.Next()));   
  5. }   

(a) public virtual int Next(int maxValue);返回一个小于所指定***值的非负随机数。 参数:maxValue-要生成的随机数的上限。maxValue 必须大于或等于零。

(b) image.SetPixel(int x,int y,Color color); 参数: x-要设置的像素的 x 坐标;y-要设置的像素的 y 坐标;color-Color 结构,它表示要分配给指定像素的颜色。

(c) Color.FromArgb(int argb) 参数:argb-指定 32 位 ARGB 值的值。

(3)把产生的随机数以字体的形式写入位图:Graphics.DrawString(string s,Font font,Brush brush,float x,float y);

参数:s-要绘制的字符串;font-Font 对象,它定义字符串的文本格式;

brush-Brush 对象,它确定所绘制文本的颜色和纹理;

x-所绘制文本的左上角的 x 坐标;

y-所绘制文本的左上角的 y 坐标。(在指定位置并且用指定的 Brush 和 Font 对象绘制指定的文本字符串)

(4) 画图片的边框线: public void DrawRectangle(Pen pen, int x, int y, int width, int height);绘制由坐标对、宽度和高度指定的矩形。

参数:pen-Pen 对象,它确定矩形的颜色、宽度和样式;

x-要绘制的矩形的左上角的 x 坐标;

y-要绘制的矩形的左上角的 y 坐标;

width-要绘制的矩形的宽度;height-要绘制的矩形的高度。

(5) 将图片以二进制流的方式输出加上格式并可显示出来。

以上就是asp.net1.1中验证码产生的原理及其应用。

【编辑推荐】

  1. ASP.NET MVC jQuery删除链接
  2. ASP.NET MVC框架中引入JQUERY JQRTE控件
  3. ASP.NET MVC 示例项目:Suteki.Shop
  4. ASP.NET MVC三层架构实例
  5. ASP.NET MVC架构中依赖性注入的概念
责任编辑:book05 来源: cnblogs
相关推荐

2009-07-29 14:59:26

asp.net1.1ASP.NET2.0

2009-07-29 15:17:42

验证控件ASP.NET1.1ASP.NET2.0

2009-07-29 15:51:29

ASP.NET中执行w

2009-07-29 11:46:22

asp.net1.1

2009-07-29 15:26:43

ASP.NET连接Or

2009-07-29 15:42:37

asp.net1.1开

2009-07-29 15:58:54

静态文件处理ASP.NET

2009-07-29 11:29:16

ASP.NET1.1ASP.NET2.0

2009-07-29 15:06:16

asp.net1.1asp.net2.0

2009-11-26 10:48:59

PHP验证码

2013-06-19 10:19:59

2009-08-05 13:09:17

ASP.NET应用执行

2010-01-08 13:46:30

VB.NET中文验证码

2021-01-19 10:29:34

短信验证码密码

2022-02-11 07:10:15

验证码

2020-11-16 07:28:53

验证码

2017-05-16 14:18:08

2011-11-02 12:43:33

2011-11-02 16:46:41

点赞
收藏

51CTO技术栈公众号